一尘不染

NodeJS |集群:如何将数据从母版发送到所有或单个子女/工人?

node.js

我有来自节点的工作(股票)脚本

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发送到主进程。但是如何将数据从主机发送到工人?举例说明,如果可能的话。


阅读 171

收藏
2020-07-07

共1个答案

一尘不染

由于cluster.fork是在child_process.fork之上实现的,因此您可以使用来将消息从主服务器发送到工作服务器,而可以通过将消息从worker.send({ msg: 'test' })工作服务器发送到主服务器process.send({ msg: 'test' });。您会收到以下消息:(worker.on('message', callback)从工作人员到主服务器)和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);
}
2020-07-07