Node.js:集群中的限制分支

时间:2017-07-05 15:20:22

标签: node.js

我有一个Web应用程序和一个在后台运行的应用程序,这最后加载了很多服务器,到目前为止一直运行正常,但在最后一个版本中添加新功能,带来了大量的负载并阻塞了服务器。

我一直在尝试修改运行群集的代码,但总是加载相同数量的进程。

这是我的代码:

var cluster = require('cluster'),
    limitWorkers = Math.ceil(require('os').cpus().length / 2),
    jobWorkers = [],
    webWorkers = [];

if(cluster.isMaster) {

    //let limit = 0;

    require('os').cpus().forEach(function() {

        addWebWorker();

        /*if(limit < limitWorkers) {

            limit++;

            addJobWorker();
        }*/
        if( limitWorkers > 0 ) {

            --limitWorkers;

            addJobWorker();
        }
    });

    cluster.on('exit', function(worker, code, signal) {

        if (jobWorkers.indexOf(worker.id) != -1) {

            console.log('job worker ' + worker.process.pid + ' died. Trying to respawn...');

            removeJobWorker(worker.id);

            addJobWorker();
        }

        if (webWorkers.indexOf(worker.id) != -1) {


            console.log('http worker ' + worker.process.pid + ' died. Trying to respawn...');

            removeWebWorker(worker.id);

            addWebWorker();
        }
    });

} else {

    console.log('start http server: ' + cluster.worker.id);
    require('./apps/web-http'); //initialize the http server here

    //if( process.env.job === 1 ){
    if( jobWorkers.indexOf(cluster.worker.id) != 1 ) {

        //if( limitWorkers > 0 ) { 

            //limitWorkers--;

            console.log('start job server: ' + cluster.worker.id);
            require('./apps/jobs-worker'); //initialize the job here
        //}
    }
}

function addWebWorker() {

    webWorkers.push(cluster.fork({web: 1}).id);
}

function addJobWorker() {

    jobWorkers.push(cluster.fork({job: 1}).id);
}

function removeWebWorker(id) {

    webWorkers.splice(webWorkers.indexOf(id), 1);
}

function removeJobWorker(id) {

   jobWorkers.splice(jobWorkers.indexOf(id), 1);
}

是否有任何想法将工作者运行一半的处理器核心或仅一个?感谢。

0 个答案:

没有答案