Simple way to send events or messages between PM2 instances
Asked Answered
H

1

7

I am looking for the simplest way to communicate a message to all the clusters of PM2, something as simple as using eventEmitter "emit" and "on" functions.

I would like to avoid using third party tools like RabbitMQ and rely only on native Node or NPM. So far I've looked at

  • ipchannel, which is a very simple solution but stops working when the PM2 process reloads
  • distributed-eventemitter, which requires STOMP and make the whole setup more complicated

I'm looking forward to your suggestions

Halfmast answered 20/5, 2020 at 15:50 Comment(2)
Have you tried gulp?Canner
I use gulp for my frontend development but I cannot see how it can do what I'm looking forHalfmast
R
9

you can use PM2 themselves

it is for accessibility to all of your pm2 app instants :

let pm2 = require('pm2');




var pm2_worker_ids = [];

pm2.connect(function (err) {

    pm2.list(function (err, data) {

        for (var i in data) {
            if (data.hasOwnProperty(i)) {
                pm2_worker_ids.push(data[i].pm2_env.pm_id);
            }
        }

        pm2.disconnect(function () {});
    });
});

it is simple send event :

if (pm2_worker_ids.hasOwnProperty(i)) {

        let data = {yourData:"you can make custom data"};

        pm2.sendDataToProcessId(pm2_worker_ids[i], {
            type: 'some random text',
            data: data,
            id: pm2_worker_ids[i],
            topic: 'some random text'
        }, function (err, res) {});

    }

it is listen to the your events :

process.on('message', function (data) {
    console.log('your actual data object', data.data);
});
Rhyme answered 18/6, 2020 at 16:23 Comment(5)
This is a neat solution!Halfmast
yes this is best solution. Isn't this the good solution for you? Why?Rhyme
I've accepted the answer, so I think i confirmed it's a good solution. (Personally I ended up using Redis which was easier to set up than expected)Halfmast
Redis pub/sub is better if you have your node instances on different servers.Tindle
still a good answer for same-server PM2 processesConsecrate

© 2022 - 2024 — McMap. All rights reserved.