首页 > 代码库 > Node项目通过cluster API充分利用多核CPU

Node项目通过cluster API充分利用多核CPU

默认的一个Node项目只有一个Master进程,通过cluster API来管理此进程,可以为每核增加一个worker,就叫分支进程吧

技术分享

示例

var cluster = require(‘cluster‘);
var http = require(‘http‘);
//获取服务器的CPU核数
var numCPUs = require(‘os‘).cpus().length;
if (cluster.isMaster) {
    for (var i = 0; i < numCPUs; i++) {
        //为CPU的每核创建一个分支进程
        cluster.fork();
    }
    cluster.on(‘death‘, function(worker) {
        console.log(‘Worker ‘ + worker.pid + ‘ died.‘);
    });
} else {
    http.Server(function(req, res) {
        res.writeHead(200);
        res.end(‘I am worker ID ‘ + process.env.NODE_CLUSTER_ID);
    }).listen(8000);
}

由于主进程与分支进程分别在不同的操作系统进程中,它们不能共享全局变量,cluster API提供了主进程与分支进程之间通信的方法

var cluster = require(‘cluster‘);
var http = require(‘http‘);
var numCPUs = require(‘os‘).cpus().length;
var workers = {};
var requests = 0;

if (cluster.isMaster) {
	for (var i = 0; i < numCPUs; i++) {
		workers[i] = cluster.fork();
		(function (i) {
			workers[i].on(‘message‘, function(message) {
				if (message.cmd == ‘incrementRequestTotal‘) {
					requests++;
					for (var j = 0; j < numCPUs; j++) {
						workers[j].send({
							cmd: ‘updateOfRequestTotal‘,
							requests: requests
						});
					}
				}
			});
		})(i);
	}
    cluster.on(‘death‘, function(worker) {
    	console.log(‘Worker ‘ + worker.pid + ‘ died.‘);
    });
} else {
	process.on(‘message‘, function(message) {
		if (message.cmd == ‘updateOfRequestTotal‘) {
			requests = message.requests;
		}
	});
	http.Server(function(req, res) {
		res.writeHead(200);
		res.end(‘Worker ID ‘ + process.env.NODE_WORKER_ID
			+ ‘ says cluster has responded to ‘ + requests
			+ ‘ requests.‘);
		process.send({cmd: ‘incrementRequestTotal‘});
	}).listen(8000);
}






Node项目通过cluster API充分利用多核CPU