Nodejs Expressjs Cluster集群app.js的正确方法

时间:2016-02-17 18:42:58

标签: node.js express web cluster-computing

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

选项A:创建一次app实例,并在创建的每个fork上调用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:创建应用程序并在每次有分支时调用listen。

     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');});
    }

1 个答案:

答案 0 :(得分:1)

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

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

请注意这个块:

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

如果它是一个子进程,你只能让Express对象监听一个端口;在创建Express对象时,在选项A中var app = express();块之外调用else是没有意义的,但它不在主进程中使用。这就是为什么你想要使用选项A的问题。

相关问题