var work_process =
cluster.fork();
}
cluster.on("listening", function(worker, address){
console.log("[master] " +
"listening: worker "+worker.id + ", pid:"+worker.process.pid + ",Address:" +
address.address + ":" + address.port);
});
cluster.on("exit", function(worker, code, signal){
console.log(‘worker ‘ +
worker.process.pid + ‘ died‘);
});
}else{
http.createServer(function(req, res){
console.log("worker" +
cluster.worker.id);
res.end("worker" +
cluster.worker.id);
}).listen(30001);
}
执行该文件会看到有多个进程现在
2:创建httpClient.js用来请求刚才创建的30001端口的服务
var http = require("http");
var optiOns= {
hostname: ‘localhost‘,
port: 30001,
path: ‘/‘,
method: ‘GET‘
};
module.exports = function(callback){
var req = http.request(options, function(res) {
res.on(‘data‘, function (chunk)
{
callback(chunk.toString());
});
});
req.on(‘error‘, function(e) {
console.log(‘problem with request:
‘ + e.message);
});
req.end();
};
3:创建test.js测试同步跑多个请求,最后统计出各个进程走的请求数量
var async = require("async");
var httpClient =
require("./httpClient");
var sum = 10;
var t = {"1":0, "2":0,"3":0, "4":0};
var c=0;
for(var i=0; i
async.series([
function(cb){
httpClient(function(str){
if(str ===
"worker1")
t["1"] = parseInt(t["1"] || 0) +
1;
if(str ===
"worker2")
t["2"] = parseInt(t["2"] || 0) +
1;
if(str ===
"worker3")
t["3"] = parseInt(t["3"] || 0) +
1;
if(str ===
"worker4")
t["4"] = parseInt(t["4"] || 0) +
1;
cb();
});
}
],
function(err, result){
if(err){
console.log(err);
}
c++;
if(c ==
sum){
console.log(t);
}
});
}
node cluster模块的使用和测试,布布扣,bubuko.com