Search code examples
node.jsredispublish-subscribe

redis pub/sub on multiple consumers


I have a small system with event messaging using the pub sub features of redis. I am using nodejs, with the redis library.

I made a small script to be able to make my consumers more easily, the problem is that when I receive any event, everyone runs and not just the one I want.

This is my script:

const redis = require("redis");
const subscriberClient = redis.createClient(redisConf);

const subscribe = (event, callback) => {
  subscriberClient.on("message", (channel, message) => {
    console.log("log: ", { channel, message });
    callback(JSON.parse(message));
  });
  subscriberClient.subscribe(event);
};

Then, in my consumers i call it like this:

const init = () => {
  eventHandler.subscribe("userWasRegistered", message => console.log("save the registered user here", message)
  );
};

Another consumer like this:

const init = () => {
      eventHandler.subscribe("publicationWasCreated", message => console.log("save the publication data", message)
      );
    };

I call all my consumers in a single file to execute all and then can listen events:

userWasRegistered.init();
publicationWasCreated.init();

The problem is when i send for example a "userWasRegistered" event, publicationWasCreated is called too, for some reason this is also listen the others events.

How can i fix it? What im doing wrong here? my script sure is the problem, but i dont know why


Solution

  • ok, i can fix it with a simple if, i only verify if channel and event are the same:

    const subscribe = (event, callback) => {
      subscriberClient.on("message", (channel, message) => {
        console.log("channel: ", channel);
        console.log("event: ", event);
    
        if (channel === event) {
          console.log("log: ", { channel, message });
          callback(JSON.parse(message));
        }
      });
      subscriberClient.subscribe(event);
    };
    

    is not the most beautifull way to do this, but it works.

    I will leave the question open for a while longer if there is a better answer.