php_nub_qq
php_nub_qq

Reputation: 16055

Message from worker to worker in a nodejs cluster

When I create a clustered app like

var cluster = require('cluster');

if (cluster.isWorker) {
  console.log('Worker ' + process.pid + ' has started.');
}

if (cluster.isMaster) {
  console.log('Master ' + process.pid + ' has started.');

  // Fork workers.
  for (var i = 0; i < require("os").cpus().length; i++) {
    var worker = cluster.fork();
  }
}

And then run it with pm2 in cluster mode

pm2 start index.js -i 0

My isMaster part never runs, I assume this is due to pm2 being the master while starting my app thus it never gets to be master, so here comes the problem. I need to be able to have communication between my workers because they keep websocket connections and that seems like the only way to broadcast stuff. What are the options?

If I run it without cluster mode (pm2 start index.js) then everything seems to execute as expected but then I only get a single process in pm2 list which is a bummer, if there is a way to get around that and have pm2 display all the child processes separately without using its cluster mode I'd be happy with that solution as well.

Upvotes: 0

Views: 1791

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40444

If you want to use process.message you won't be able to use pm2 cluster mode, since process.message sends messages to master.

If you want to use pm2 cluster mode, you have to use another way of communication between workers, such as Redis,RabbitMQ, Unix Sockets.

There are some packages that will allow you to setup an IPC communication very easily, for example: node-ipc

Upvotes: 4

Related Questions