0

Apache Web Server 有一个名为 MaxRequestsPerChild 的配置参数。 http://httpd.apache.org/docs/2.0/en/mod/mpm_common.html#maxrequestsperchild “MaxRequestsPerChild 请求后,子进程会死掉。”

为了避免由于内存泄漏、连接过多或其他意外错误导致的崩溃,在使用 node.js Cluster 模块时我应该做同样的事情吗?

*我在 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);
}

到目前为止,这一直运作良好,但我想知道还有更合适的方法。

4

1 回答 1

1

MaxRequestsPerChild 可以很好地隐藏内存泄漏问题,但不应该经常使用,因为它只是隐藏了真正的问题。首先尽量避免内存泄漏。不应使用它来避免其他问题,例如连接过多或其他意外错误。

当您使用 MaxRequetsPerChild 时,您不应该process.kill两者都使用process.exit,因为这会立即关闭所有正在进行的连接。

相反,您应该server.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

于 2013-09-25T17:37:31.973 回答