首页 > 其他 > 详细

node cluster模块的使用和测试

时间:2014-03-27 18:03:51      阅读:474      评论:0      收藏:0      [点我收藏+]

首先安装async包

用到的有http、cluster包

http和cluster都会node自带的包,无需安装

1:创建cluster.js,代码如下,更具cpu创建多个进程

var cluster = require("cluster");
var http = require("http");
var numCPUs = require(‘os‘).cpus().length;

if(cluster.isMaster){

    console.log("[master] " + "start master......");

 

    var data = 0;

    for(var i=0; i<numCPUs; i++){

        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<sum; 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

node cluster模块的使用和测试

原文:http://www.cnblogs.com/ajun/p/3628716.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!