node.js-v0.8API解读(4)- Cluster
by snoopyxdy
at 2012-07-03 16:41:18
original http://snoopyxdy.blog.163.com/blog/static/601174402012631365989
是一个只读的对象,对象有3个key
返回一个布尔值,表示当前进程是否是Master主进程,同理cluster.isWorker
简单解释下以上代码,当我们批量fork了几个worker后,就会触发fork事件了,于是我们为每一个worker设定了一个timeout。var timeouts = [];
function errorMsg() {
console.error("Something must be wrong with the connection ...");
}
cluster.on('fork', function(worker) {
timeouts[worker.id] = setTimeout(errorMsg, 2000);
});
cluster.on('listening', function(worker, address) {
clearTimeout(timeouts[worker.id]);
});
cluster.on('exit', function(worker, code, signal) {
clearTimeout(timeouts[worker.id]);
errorMsg();
});
cluster.on('online', function(worker) {
console.log("Yay, the worker responded after it was forked");
});
cluster.on('listening', function(worker, address) {
console.log("A worker is now connected to " + address.address + ":" + address.port);
});
cluster.on('exit', function(worker, code, signal) {
if (worker.suicide === true) {
console.log('Oh, it was just suicide\' – no need to worry').
}
});
// destroy worker
worker.destroy();
if (cluster.isMaster) {
var worker = cluser.fork();
var timeout;
worker.on('listening', function(address) {
worker.disconnect();
timeout = setTimeout(function() {
worker.send('force kill');
}, 2000);
});
worker.on('disconnect', function() {
clearTimeout(timeout);
});
} else if (cluster.isWorker) {
var net = require('net');
var server = net.createServer(function(socket) {
// connection never end
});
server.listen(8000);
server.on('close', function() {
// cleanup
});
process.on('message', function(msg) {
if (msg === 'force kill') {
server.destroy();
}
});
}