While Redis is popular as a caching and data storage solution for application, it is also a great tool to implement a publish-subscribe interaction. However, publish-subscribe pattern often sounds complicated to implement. On the contrary, implementing Redis PubSub in NodeJS is quite simple and straightforward.
To implement Redis PubSub in NodeJS app, we need a Redis instance and a Redis client. The Redis client will connect our NodeJS application to the Redis server instance. Important aspect is to configure the publisher and subscriber to transfer data.
1 – What is Redis PubSub?
Redis supports the publish/subscribe messaging paradigm.
In the publish/subscribe messaging pattern, publishers don’t send messages or data directly to subscribers. Instead, publishers send the message to a channel. One or more subscribers can subscribe to this channel in order to receive the messages. In other words, the pub/sub pattern is a fire-and-forget approach from the publisher’s perspective.
In Redis PubSub, the Redis instance acts as the bridge between publishers and subscribers. A publisher publishes the message along with an identifying topic name. You can think of the topic name as a channel. Subscribers subscribe to the topic. Whenever a new message is published for a topic, subscribers can listen to the message and act upon them.
Now that we understand the what Pub Sub is, let us build a small sample application to see the pattern in action.
2 – Installation of Packages
To demonstrate the Redis PubSub in NodeJS, we will create two applications – one as a publisher and the second as the subscriber.
See below for the project setup for the publisher application
$ mkdir publisher
$ npm init -y
$ npm install --save redis express
Similarly, we can setup the subscriber application.
$ mkdir subscriber
$ npm init -y
$ npm install --save redis express
The redis package provides support for connecting to a Redis instance. On the other hand, the express package helps us create a NodeJS webserver that can listen to incoming requests.
3 – Creating the Redis NodeJS Publisher
With the respective projects ready, we can now write the logic for the Redis NodeJS Publisher.
See below example:
const express = require('express');
const redis = require('redis');
const publisher = redis.createClient()
publisher.connect()
const app = express()
app.get("/", (req, res) => {
const message = {
msg: "Hello, World"
}
publisher.publish('test', JSON.stringify(message))
res.send("Published Event Using Redis");
})
app.listen(3000, () => {
console.log('Server is listening on port 3000');
})
Technically, this is a very simple application. We call the redis.createClient() to get an instance of the Redis client. Next, we call the connect method in order to establish the connection.
Note that this statement expects a Redis instance to be running on localhost port 6379.
To publish a message, we use the publish() method. This method takes two parameters as input. First is the topic or channel (in this case, test). The second is the actual message string.
We invoke the Redis publish functionality when user triggers the http://localhost:3000 request handler.
4 – Creating the Redis NodeJS Subscriber
Next, we can create the subscriber part of the Redis PubSub pattern.
See below example:
const express = require("express")
const redis = require("redis")
const subscriber = redis.createClient()
subscriber.connect()
const app = express()
subscriber.subscribe('test', (message) => {
console.log(message);
});
app.get("/", (req, res) => {
res.send("Subscriber One")
})
app.listen(3001, () => {
console.log("server is listening to port 3001")
})
We can create an instance of the Redis Client using createClient() function and connect to the instance.
To subscribe to the message, we use the subscribe() function. Basically, this function takes two inputs. First is the topic or channel name (in this case, we use test again). The second argument is a callback function that has the message as payload.
We can process the message within the callback function. In our example, we simply print the message to console.
Note that we start the subscriber application on a different port (3001) since the host is same.
5 – Conclusion
Redis Pub Sub in NodeJS makes it extremely simple to build applications using the publish-subscribe pattern. In this post, we looked at the pub sub pattern with simple examples.
Want to learn more applications of Redis? Check out this post on Redis Pipeline with NodeJS.
If you have any comments or queries about this post, please feel free to mention them in the comments section below.
0 Comments