首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。