[英]Is rotating child processes in node.js/cluster good idea?
Apache Web Server具有一个名为MaxRequestsPerChild的配置参数。 “ http://httpd.apache.org/docs/2.0/en/mod/mpm_common.html#maxrequestsperchild ”在MaxRequestsPerChild请求之后,子进程将死亡。
为避免内存泄漏,过多的连接或其他意外错误导致的崩溃,在使用node.js群集模块时我应该做同样的事情吗?
*我在node.js而不是Apache之前使用Nginx。 我提到它是为了便于解释。
我只是这样实现它:
var maxReqsPerChild = 10; // Small number for debug
var numReqs = 0;
if (cluster.isMaster) {
var numCPUs = require('os').cpus().length;
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('death', function(worker) {
// Fork another when one died
cluster.fork();
});
} else {
http.createServer(function(webReq, webRes) {
// Count up
numReqs++;
// Doing something here
// Kill myself
if (numReqs > maxReqsPerChild) {
process.kill(process.pid); // Or more simply, process.exit() is better?
}
}).listen(1338);
}
到目前为止,它一直工作良好,但是我想知道还有没有更合适的方法。
MaxRequestsPerChild可以很好地隐藏内存泄漏问题,但不应经常使用,因为它只会隐藏真正的问题。 首先尝试避免内存泄漏。 它不应用于避免其他问题,例如连接过多或其他意外错误。
当您使用MaxRequetsPerChild时,您既不应process.kill
也不process.exit
,因为这会立即关闭所有正在进行的连接。
相反,您应该使用server.close
,它将等待所有正在进行的连接完成,然后触发“ close”事件。
var server = http.createServer(...);
server.on( "close", function() {
process.exit(0);
});
server.on( "request", function () {
requestCount += 1;
if ( options.max_requests_per_child && (requestCount >= options.max_requests_per_child) ) {
process.send({ cmd: "set", key: "overMaxRequests", value: 1 });
if ( ! server.isClosed ) {
server.close();
server.isClosed = 1;
}
}
});
在此处查看完整的工作示例: https : //github.com/mash/node_angel
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.