这个NodeJS集群主机可以崩溃吗?

时间:2016-01-11 05:15:43

标签: node.js express restart forever node-cluster

我们一直在使用forever启动我们的Express应用程序,该应用程序使用cluster来生成完成所有工作的工作人员。这意味着master只运行此代码:

if (cluster.isMaster) {

    // ...
    // ... check arguments and do some initial prep 
    // ...

    // Create a worker for each CPU
    for (var i = 0; i < cpuCount; i += 1) {
        cluster.fork();
    }

    // Listen for dying workers
    cluster.on('exit', function (worker) {
        if (!worker.suicide) {
            // Replace the dead worker if not a startup error like port in use.
            console.log('Worker ' + worker.id + ' died. Replacing it.');
            cluster.fork();
        }
    });
    return;
}

鉴于主人并没有真正做任何事情,是否需要&#34;保护&#34;它与foreversupervisor等?是否存在主机可能崩溃的情况,并且自动重启它会有价值吗?

1 个答案:

答案 0 :(得分:1)

在我看来,没有必要监控群集中的主进程,因为您无法处理SIGKILL

请参阅PM2 implementation as below,实际上是master

var cluster = require('cluster');  
var http    = require('http');  
var os      = require('os');

var numCPUs = os.cpus().length;

if (cluster.isMaster) {  
  // Master:
  // Let's fork as many workers as you have CPU cores

  for (var i = 0; i < numCPUs; ++i) {
    cluster.fork();
  }
} else {
  // Worker:
  // Let's spawn a HTTP server
  // (Workers can share any TCP connection.
  //  In this case its a HTTP server)

  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end("hello world");
  }).listen(8080);
}