1

我们一直在使用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;
}

鉴于主人并没有真正做任何事情,是否有必要用 , 等“保护”foreversupervisor?是否存在master可能崩溃并且自动重新启动它的价值的任何情况?

4

1 回答 1

1

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

参考下面的实现,实际上是这样。PM2 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);
}
于 2016-01-11T06:30:48.557 回答