Can someone do an code example for me using node.js natives cluster?
Lets say I have this code and want each 'X' to be balanced between my cores, how would I do that?
var y = {};
var i = 0;
var X = require('x.js');
wss.on('connection', function(ws) {
console.log("client connected sucessfully");
ws.on('message', function(obj) {
for(var a = 0; a < 100; a++){
y[i] = new X();
i++;
}
});
});
There's a good example on the node cluster documentation page . In short, you want to use cluster.fork()
to create a new worker. The worker will execute the same code that master does, so your example would become something like this:
var y = {};
var i = 0;
var X = require('x.js');
if (cluster.isMaster) {
for (var worker_num = 0; worker_num < 10; worker_num++) {
cluster.fork();
}
} else {
wss.on('connection', function(ws) {
console.log("client connected sucessfully");
ws.on('message', function(obj) {
for(var a = 0; a < 100; a++){
y[i] = new X();
i++;
}
});
});
}
However in reality you would need way more than that. You'd want features like automatic worker restarts, heartbeats, etc etc, so writing good cluster managing code is a big task by itself. I suggest using some ready solution pm2 or service-runner
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.