I want to use Cluster module of nodejs but when event trigger,when the first worker capture it,other ones don't do anything.
var cluster = require('cluster')
numCPUs = require('os').cpus().length;
if (cluster.isMaster){
for (var i = 0; i < numCPUs; i++)
cluster.fork();
cluster.on('exit', function(worker, code, signal) {
cluster.fork();
});
} else {
var redis = require('redis');
var client = redis.createClient();
client.on('message',function(channel,message){
console.log(channel,message);
});
client.subscribe("CH_IP");
}
The above code has below output
CH_IP {"LOC":"OTHER","PID":1,"SID":1}
CH_IP {"LOC":"OTHER","PID":1,"SID":1}
CH_IP {"LOC":"OTHER","PID":1,"SID":1}
CH_IP {"LOC":"OTHER","PID":1,"SID":1}
CH_IP {"LOC":"OTHER","PID":1,"SID":1}
CH_IP {"LOC":"OTHER","PID":1,"SID":1}
CH_IP {"LOC":"OTHER","PID":1,"SID":1}
CH_IP {"LOC":"OTHER","PID":1,"SID":1}
How to edit code to only run one console.log
?
The fork
method accepts an object of key/pair values, which gets added to the workers process environment. You can use this to identify each worker, and single out one to do the work:
if (cluster.isMaster){
for (var i = 0; i < numCPUs; i++)
cluster.fork({ workerId: i+1 });
// etc...
} else {
if(process.env.workerId == 1){
// do stuff
}
}