Search code examples
node.jsredismicroserviceshapi.jsredis-streams

Make two microservices hosted on different machine communicate with each other using Redis Pub/Sub


I have two diiferent microserivice and one API Gateway. All hosted on different machine. I want both microservice communicate with each other using Redis Pub/Sub.

I am able to make them talk to each other while all the microservice are hosted on same machine but I am not able to make them talk with each other while they are hosted on different machines.

Currently I am making them communicate with other while hosted on same machine using the following code

Subsciber

    const client = redis.createClient();
    const subscriber = client.duplicate();
    await subscriber.connect();

    await subscriber.subscribe('user-notify', (message) => {
        console.log('user-notify', message);
    });

Publisher

    const publisher = redis.createClient();

    await publisher.connect();
    publisher.publish("user-notify", "Server Started");

Solution

  • In order to solve this I am installing redis to server and passing the host and port as args to redis.createClient();

    For Eg,

    Let's say the ip of redis server is 17.52.123.12 and post is 5556

    Subsciber

        const client = redis.createClient(
             host: '17.52.123.12',
             port: '5556'
        );
        const subscriber = client.duplicate();
        await subscriber.connect();
    
        await subscriber.subscribe('user-notify', (message) => {
            console.log('user-notify', message);
        });
    

    Publisher

        const publisher = redis.createClient(
             host: '17.52.123.12',
             port: '5556'
        );
    
        await publisher.connect();
        publisher.publish("user-notify", "Server Started");