节点群集:如何为每个工作人员分配单独的服务器/端口?

时间:2015-08-02 00:24:29

标签: node.js node-cluster

我知道我可以使用节点cluster模块来创建几个所有服务于同一套接字连接的工作者(例如来自docs):

var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
  // 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\n");
  }).listen(8000);
}

但是,如果我不是为同一个连接提供服务而是希望每个工作者都运行自己的服务器,每个服务器都在一个单独的端口上监听呢?

1 个答案:

答案 0 :(得分:6)

您可以将环境变量传递给每个子进程,允许主进程为其分配端口:

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  var pidToPort = {}; 
  var worker, port;
  for (var i = 0; i < numCPUs; i++) {
    port = 8000 + i;
    worker = cluster.fork({port: port});
    pidToPort[worker.process.pid] = port;
  }

  console.log(pidToPort);

  cluster.on('exit', function(worker, code, signal) {
    // Use `worker.process.pid` and `pidToPort` to spin up a new worker with
    // the port that's now missing.  If you do so, don't forget to delete the
    // old `pidToPort` mapping and add the new one.
    console.log('worker ' + worker.process.pid + ' died');
  }); 
} else {
  // Start listening on `process.env.port` - but first, remember that it has
  // been cast to a string, so you'll need to parse it.
  console.log(process.env.port);
}