2012-06-22 17 views
0

Apache Web Server具有名为MaxRequestsPerChild的配置参数。 http://httpd.apache.org/docs/2.0/en/mod/mpm_common.html#maxrequestsperchild “MaxRequestsPerChild请求后,子进程将会死亡。”在node.js/cluster中旋转子进程的好主意?

为避免因内存泄漏,连接太多或其他意外错误导致挤压,我应该在使用node.js群集模块时做同样的事情吗?

*我在node.js前面使用Nginx,而不是Apache。我提到它,以便我可以轻松解释。

我只是实现它是这样的:

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

这一直行之有效到现在为止,但我不知道还有更合适的方法。

+0

process.exit()是更好的。 – Mustafa

+0

谢谢你,穆斯塔法。我尝试使用process.exit(),但是这种方法导致了一个基本问题 - 也就是说,当process.exit(或process.kill)时,同一时刻的所有其他请求都会死亡,而不会响应客户端。 – chikaram

回答

1

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

相关问题