我正在测试NodeJS的集群模块。我正在努力实现以下目标:
我面临的问题是:
我的代码是:
var cluster = require('cluster');
var http = require('http');
var numCPUs = 2;
var workerStatus = new Object();
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
cluster.fork();
console.log('worker %d died (%s). restarting...', worker.process.pid, signal || code);
});
// Go through all workers
function eachWorker(callback) {
for (var id in cluster.workers) {
callback(cluster.workers[id],id);
}
}
setInterval(function (){
eachWorker(function(worker,id) {
if (workerStatus[id] == undefined) workerStatus[id]=-1;
if (workerStatus[id] < 4){
workerStatus[id]++;
console.log("Message Sent : " + id);
worker.send('check');
}else{
delete workerStatus[id]
console.log("Some Problem with " + id);
worker.disconnect();
worker.kill();
}
});
},5000);
eachWorker(function(worker,id){
var w_id =id;
worker.on('message', function(msg){
workerStatus[w_id]=0;
console.log("Message Received : " + w_id);
});
});
} else {
process.on('message', function(msg) {
process.send(msg);
});
// Workers can share any TCP connection
// In this case its a HTTP server
http.createServer(function(req, res) {
while (1) {}
res.writeHead(200);
res.end("hello world--" + cluster.worker.id);
//cluster.worker.kill();
}).listen(8080);
}
答案 0 :(得分:1)
我发现了这个问题。
当我杀死工作者并启动一个新工作者时,我没有为新创建的工作添加一个监听器。因此,从未收到新创建的工作人员的消息。
只需添加以下代码,问题就解决了。
cluster.on('exit', function(worker, code, signal) {
var w = cluster.fork();
console.log('worker %d died (%s). restarting...', worker.process.pid, signal || code);
w.on('message', function(msg){
workerStatus[w.id]=0;
console.log("Message Received : " + w.id);
});
});
答案 1 :(得分:0)
我有一个简单的支持模块,用于分隔工作程序脚本(并仅加载不同的脚本+处理通信),这可能会有所帮助:runworker