Is there a way to send a message from a worker to other workers in node.js?

不想你离开。 提交于 2019-12-12 02:42:41

问题


I can use process.send to send a message from a worker to a master. I can use the following code to send a message from the master to each worker.

for (var id in cluster.workers) {
  cluster.workers[id].send({command: 'doSomething'});
}

To send a message from a worker to other workers I have to send a message to the master and then have it forward the message. This results in the original sender also receiving the message and is something that I'd like to avoid but I can live with it!

I also tried sending the message directly from the worker like it's done in the master but cluster.workers is undefined in workers.

Is there any other way to do this?


回答1:


You can compare pid's of the sender and the recipients:

worker.on('message', function(msg) {

  for (var id in cluster.workers) {

    if (cluster.workers[id].process.pid !== this.process.pid) {

      cluster.workers[id].send({
        command: 'doSomething',
        from: this.process.pid
      });

    }

  }

}



回答2:


I have created a simple package called ipc-messenger that helps to do this. It provides an abstraction where details are hidden from the user.

The function messageSiblings can be used to send messages only to other workers and messageWorkers to send messages to all workers.

Example:

var ipcm = require('ipc-messenger')
ipcm.messageSiblings('hello')


来源:https://stackoverflow.com/questions/35463203/is-there-a-way-to-send-a-message-from-a-worker-to-other-workers-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!