一个工人在nodejs中监听事件

时间:2014-03-03 20:34:00

标签: node.js worker

我想使用nodejs的Cluster模块,但是当事件触发时,当第一个worker捕获它时,其他的不执行任何操作。

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");    
}

以上代码具有以下输出

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}

如何编辑代码只运行一个console.log

1 个答案:

答案 0 :(得分:1)

fork方法接受键/对值的对象,该对象将添加到工作进程环境中。您可以使用它来识别每个工作人员,并选出一个来完成工作:

if (cluster.isMaster){
    for (var i = 0; i < numCPUs; i++)
        cluster.fork({ workerId: i+1 });
    // etc...
} else {
    if(process.env.workerId == 1){
        // do stuff
    }
}