cluster模块实现多进程-让我的代理服务速度飞起来了

cluster模块实现多进程

现在的cluster已经可以说完全做到的负载均衡,在做代理服务和http服务器的时候能够讲服务器性能发挥到最大。来看一下具体的实现吧

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; 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);
var num = 0;
http.createServer(function (req, res) {
num++;
console.log('worker'+cluster.worker.id+":"+num);
res.end('worker'+cluster.worker.id+',PID:'+process.pid);
}).listen(3000);
}

分开的写法 ,业务逻辑完全独立出来

加上console.log('Worker #' + cluster.worker.id + ' make a response');这句代码可以打印出是哪个进程处理该请求。

var cluster = require('cluster');
var numCPUs = require('os').cpus().length; if (cluster.isMaster) {
console.log('[master] ' + "start master..."); for (var i = 0; i < numCPUs; 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) {
require('app.js');
}
//app.js就是开启具体的业务逻辑了 //app.js具体内容
const net = require('net');
//自动创建socket
const server = net.createServer(function(socket) { //'connection' listener
socket.on('end', function() {
console.log('server disconnected');
});
socket.on('data', function() {
socket.end('hello\r\n');
});
});
//开启端口的监听
server.listen(8124, function() { //'listening' listener
console.log('working')
});

参考相关文档

https://github.com/aleafs/node-cluster

http://cnodejs.org/topic/4f293a91aa8e490b110214fd

http://blog.fens.me/nodejs-core-cluster/

http://www.cnblogs.com/CodeGuy/archive/2013/05/27/3101312.html

http://blog.chinaunix.net/uid-26983585-id-4035676.html

https://github.com/xk/node-threads-a-gogo

http://www.jianshu.com/p/f8f91ac8d3bc

上一篇:6 tips for recovering from a flop


下一篇:linux install StarDict