微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js – NodeJS | Cluster:如何从master发送数据到所有或单个子/ worker?

我有工作(股票)脚本从 node

var cluster = require('cluster');
var http = require('http');
var numReqs = 0;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < 2; i++) {
    var worker = cluster.fork();

    worker.on('message',function(msg) {
      if (msg.cmd && msg.cmd == 'notifyRequest') {
        numReqs++;
      }
    });
  }

  setInterval(function() {
    console.log("numReqs =",numReqs);
  },1000);
} else {
  // Worker processes have a http server.
  http.Server(function(req,res) {
    res.writeHead(200);
    res.end("hello world\n");
    // Send message to master process
    process.send({ cmd: 'notifyRequest' });
  }).listen(8000);
}

在上述脚本中,我可以轻松地将数据从worker发送到master进程.但是如何从主人员发送数据到工作人员?举个例子,如果可能的话.

解决方法

因为cluster.fork是在 child_process.fork之上实现的,所以你可以使用worker.send({msg:’test’})从master发送消息,通过process.send({msg :’test’});.你收到如下消息:worker.on(‘message’,callback)(从worker到master)和process.on(‘message’,callback); (从主人到工作人员).

这是我的完整示例,您可以通过浏览http://localhost:8000/进行测试然后工作人员将向主人发送消息,主人将回复

var cluster = require('cluster');
var http = require('http');
var numReqs = 0;
var worker;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < 2; i++) {
    worker = cluster.fork();

    worker.on('message',function(msg) {
      // we only want to intercept messages that have a chat property
      if (msg.chat) {
        console.log('Worker to master: ',msg.chat);
        worker.send({ chat: 'Ok worker,Master got the message! Over and out!' });
      }
    });

  }
} else {
  process.on('message',function(msg) {
    // we only want to intercept messages that have a chat property
    if (msg.chat) {
      console.log('Master to worker: ',msg.chat);
    }
  });
  // Worker processes have a http server.
  http.Server(function(req,res) {
    res.writeHead(200);
    res.end("hello world\n");
    // Send message to master process
    process.send({ chat: 'hey master,I got a new request!' });
  }).listen(8000);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐