zoukankan      html  css  js  c++  java
  • node cluster模块的使用和测试

    首先安装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);
            }
        });
    }

    其中Express和cluster结合使用

    创建clusterMaster.js

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

    var workerList = [];
    function createWorker(){
      var worker = cluster.fork();
      worker.on("message", function(data){
        console.log("the worker " + worker.id + "|" + worker.process.pid + " accept data: " + JSON.stringify(data));
        if(data.type && data.type === "broadcast"){
          workerList.forEach(function(wk){
            wk.send(data.body);
          });
        }
      });
      return worker;
    };

    if(cluster.isMaster){
      console.log("master process start...");
      for (var i = 0; i < numCPUs; i++) {
            workerList.push(createWorker());

      }
      cluster.on('listening',function(worker, address){
         console.log("A worker with #" + worker.id + " pid " + worker.process.pid +
            " is now connected to " + address.address + ":" + address.port);
      });
      cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
        process.nextTick(function(){ cluster.fork(); });
      });
    }else{
      require("./app.js");
    }

    以上cluster的功能就完成了,在app.js中添加监听message

    process.on("message", function(data){
      console.log("the process %s accept data: %s", process.pid, JSON.stringify(data));
    });

    在路由方法这种可以实现发送消息到master,master在.on("message")中收到消息后做操作

    process.send({type: "broadcast", body:"ssssssss"});

    以上就是node下cluster和express结合实现合理利用CPU

  • 相关阅读:
    ubuntu18 任务栏调到底部
    十六, Oracle约束
    十五, 数据导出导入
    十四, 角色
    十三,权限
    十二, 系统默认参数
    十一,函数
    PL/SQL 九九乘法表
    十,事务和锁
    九, 表查询 三
  • 原文地址:https://www.cnblogs.com/ajun/p/3628716.html
Copyright © 2011-2022 走看看