DEV Community

GaneshMani
GaneshMani

Posted on • Originally published at cloudnweb.dev

Implementing Redis Pub/Sub in Node.js Application

In this article, we will see how to implement redis pub sub in a node application.Implementing Redis Pub/Sub in Node.js Application

Change the way you create an object - Javascript weekly

Promises indide a loop - Javascript ES6

Prototypal Inheritance - Javascript

Before going into the implementation part, we will see what is pub sub and why we need it.

What is Pub/Sub

Pub/Sub is nothing but a publish subscribe model where subscriber subscribes to an event. subscriber notified when the publisher publish the event.

To explain it with a simple analogy. Let's say you want to buy a latest iPhone in Amazon. But, due to a demand. it is sold out early. Amazon asks you to get notified when it is available.

In this place you are a subscriber subscribing to an event(when stock available). Amazon is the publisher(tells the stock is available).

When publisher(Amazon) publish an event(stock available). you(Subscriber) will get notified.

Implementing Pub/Sub

Publisher

we are using Redis PubSub which is a popular inMemory database. you can also use other pub sub models like Kafka,RabbitMQ etc.

Firstly, To implement Redis PubSub in Node.js application. you need to have redis installed on your machine. Secondly, you need to run the redis server in the command line.

After that, we need npm package called redis which connects with Express app with redis.

Mainly we are going to create three app servers. one is going to be a publisher and remaining two are subscribers.

npm init --yes
npm install express redis

create a file called server.js and add the following code.

const express = require('express');
const redis = require('redis');

const publisher = redis.createClient();

const app = express();

app.get('/',(req,res) => {
    const user = {
        id : "123456",
        name : "Davis"
    }

    publisher.publish("user-notify",JSON.stringify(user))
    res.send("Publishing an Event using Redis");
})

app.listen(3005,() => {
    console.log(`server is listening on PORT 3005`);
})

we are importing redis from package.

After that, we are creating a redis client to connect with redis server.In redis, we can connect any number of clients to the redis server.

Once we connect it, we can publish an event by calling publish method

publisher.publish("user-notify",JSON.stringify(user))

we need to pass the topic name to write the data and Data .

Subscribers

create two express servers with the following code in different folder.

server.js

const express = require('express');
const redis = require('redis');

const subscriber = redis.createClient();

const app = express();

subscriber.on("message",(channel,message) => {
    console.log("Received data :"+message);
})

subscriber.subscribe("user-notify");

app.get('/',(req,res) => {
    res.send("Subscriber One");
})

app.listen(3006,() => {
    console.log("server is listening to port 3006");
})

server.js

const express = require('express');
const redis = require('redis');

const subscriber = redis.createClient();

const app = express();

subscriber.on("message",(channel,message) => {
    console.log("Received data :"+message);
})


app.get('/',(req,res) => {
    res.send("subscriber two");
})

subscriber.subscribe("user-notify");

app.listen(3007,() => {
    console.log("server is listening to port 3007");
})

Now you can run both publisher and subscribers. when you run the publisher, the publisher will publish the data to subscribers.

Demo

That's it for this article.Implementing Redis Pub/Sub in Node.js Application. To learn more about redis, you can watch a tutorial from Brad Traversy which is a great video.

Happy Coding :-)

Top comments (7)

Collapse
 
okbrown profile image
Orlando Brown • Edited

Hi, I know everyone here likes to be nice and friendly on dev.to but I truly believe some quality control is required. I'm concerned on how a new developer will be able to "connect the dots" and see how this works and how it can be useful.

Also setting up three instances of node, with Redis magically knowing where to publish events will only make a new developer scratch their head.

I like this place, but let's put some thought into why and who it is for.

Collapse
 
ganeshmani profile image
GaneshMani

i agree to your point.But IMHO, if someone is reading about redis. then it is from assumption that he might have already knew how to setup the express servers and work on it.

when i was beginner, i couldn't able to understand this kind of concepts.But, when i got my hands dirty by building things.it connects the dot automatically.i can be able to understand things clearly.

For beginner perspective, i agree to your point though.

Collapse
 
thatkazuki profile image
Desmond Edem

So how to run this now?

Collapse
 
nelsonmendezz_ profile image
Nelson Hernández

Thank you💪

Collapse
 
theprogrammer16 profile image
Tran Duong

Nice tutorial. I suggest that you should add a section about how to start Redis server locally so maybe new programmers may connect the dots.

Collapse
 
ralexand56 profile image
ralexand56

Huh? So how does it know what redis server to connect to?

Collapse
 
th3n00bc0d3r profile image
Muhammad

Gracefully simplified..Cheers Man...