首页 > 代码库 > Node.js的集群功能以及在Express的配置

Node.js的集群功能以及在Express的配置

Node.js在v0.6.0版本下内置了集群功能,作为cluster模块,用于nodejs的多核处理,也比较容易通过脚本实现一个负载均衡的集群。

 脚本参考了其他人的材料,建立一个server.js(因为虚拟机只有1核,为模拟多线程,所以采用numCPUs+4)

var cluster = require(‘cluster‘);var http = require(‘http‘);var numCPUs = require(‘os‘).cpus().length;if (cluster.isMaster) {    console.log(‘[master] ‘ + "start master...");    for (var i = 0; i < numCPUs+4; i++) {         cluster.fork();    }    cluster.on(‘listening‘, function (worker, address) {        console.log(‘[master] ‘ + ‘listening: worker‘ + worker.id + ‘,pid:‘
+ worker.process.pid + ‘, Address:‘ + address.address + ":" + address.port); });} else if (cluster.isWorker) { console.log(‘[worker] ‘ + "start worker ..." + cluster.worker.id); http.createServer(function (req, res) { console.log(‘worker‘+cluster.worker.id); res.end(‘worker‘+cluster.worker.id+‘,PID:‘+process.pid); }).listen(3000);}

 

启动服务器可以看到日志

$ node server.js[master] start master...[worker] start worker ...1[master] listening: worker1,pid:2925, Address:0.0.0.0:3000[worker] start worker ...3[master] listening: worker3,pid:2931, Address:0.0.0.0:3000[worker] start worker ...4[master] listening: worker4,pid:2932, Address:0.0.0.0:3000[worker] start worker ...2[master] listening: worker2,pid:2930, Address:0.0.0.0:3000worker4worker2worker1worker3worker4worker2worker1

通过curl访问可以看到route到不同的进程
curl 192.168.1.20:3000worker4,PID:2932curl 192.168.1.20:3000worker2,PID:2930

但如何和我们的Express框架结合起来呢,通过npm start实际上是启动了package.json上的script脚本
node ./bin/www

具体打开www文件,发现详细的创建Server的命令,所以需要直接修改这个文件.修改如下:

#!/usr/bin/env node

/**
* Module dependencies.
*/

var cluster = require(‘cluster‘);
var numCPUs = require(‘os‘).cpus().length;
var app = require(‘../app‘);
var debug = require(‘debug‘)(‘myapp-express:server‘);
var http = require(‘http‘);

if (cluster.isMaster) {
console.log(‘[master] ‘ + "start master...");

for (var i = 0; i < numCPUs+4; i++) {
cluster.fork();
}

cluster.on(‘listening‘, function (worker, address) {
console.log(‘[master] ‘ + ‘listening: worker‘ + worker.id + ‘,pid:‘ + worker.process.pid + ‘, Address:‘ + address.address + ":" + address.port);
});

} else if (cluster.isWorker) {
console.log(‘[worker] ‘ + "start worker ..." + cluster.worker.id);
http.createServer(app).listen(3000);
/*
http.createServer(app) {
console.log(‘worker‘+cluster.worker.id);
res.end(‘worker‘+cluster.worker.id+‘,PID:‘+process.pid);

}).listen(3000);*/
}



启动后能正常访问网页

技术分享

但在后台的日志中无法显示调用的process的信息所以我们不知道是否真的作到负载均衡了.

技术分享

 

研究了一下,页面还是走到routes目录下的index.js模块,所以在index.js下加入console.log信息,这样基本上访问的时候就知道是走到哪个进程实现调用

 

router.get(‘/about‘,function(req,res) {
console.log(process.pid);
res.render(‘about‘,{titile:"Introduction"});
});

 

 经过实践,同一个firefox的请求会路由到同一个进程pid,关闭在重新打开会路由到另一个pid.




Node.js的集群功能以及在Express的配置