Nodejs Expressjs群集适当的方法来群集app.js

有谁知道哪个是正确的方法来集群nodejs express应用程序,为什么?

选项A:应用程序实例创build一次,并在每个创build的叉上调用listen。

var app = require('express')(); if (cluster.isMaster) { //fork once per cpu for (var i = 0; i < numCPUs; i++) { cluster.fork(); } //if a worker is online cluster.on('online', function WorkerOnline(worker) { console.log('%s Worker is running on %s pid: ', new Date().toISOString(), worker.process.pid); }); //if a worker dies, log that and create a new one cluster.on('exit', function workerDed(worker, code, signal) { cluster.fork(); }); } else { //non-master forks listen on the ip/port specified in the config app.listen(config, function () { console.log('%s Express server listening on ip %s:%s ', new Date().toISOString(), config.ip, config.port); }); } 

选项B:创build应用程序,每次有叉时调用监听。

  if (cluster.isMaster) { //fork once per cpu for (var i = 0; i < numCPUs; i++) { cluster.fork(); } //if a worker is online cluster.on('online', function workeronline(worker) { console.log('%s Worker is running on %s pid: ', new Date().toISOString(), worker.process.pid); }); //if a worker dies, log that and create a new one cluster.on('exit', function workeronline(worker, code, signal) { cluster.fork(); }); } else { //non-master forks listen on the ip/port specified in the config var app = require('express')(); app.listen(8000, function() { console.log('Process ' + process.pid + ' is listening to all incoming requests');}); } 

要么没事。 当Node.js调用cluster.fork() ,它会运行一个新的Node实例,并重新调用您的app.js文件。 因此,行var app = express(); 可以在任何地方调用,并且可以保证与其他实例上实例化的Express对象不同(即,您的主进程和从进程不共享appvariables)。

但是,选项B更清楚地表明您每次创build新的Express实例时都是分叉的。 另外,在选项A中,您在主进程从进程上创build一个Express对象,但主进程不使用您创build的Express对象。

注意这个块:

 } else { app.listen(config, function () { console.log('%s Express server listening on ip %s:%s ', new Date().toISOString(), config.ip, config.port); }); } 

如果它是一个subprocess,你只能让Express对象在一个端口上进行侦听; 调用var app = express(); 在创build一个Express对象的时候,在选项A的else块之外是毫无意义的,但是它在主进程中没有被使用。 这引出了问题,为什么你想要使用选项A.