Implementing Redis Pub/Sub in Node.js Application

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

Originally published by ganeshmani009 at cloudnweb.dev

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.


Originally published by ganeshmani009 at cloudnweb.dev

=============================

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Learn More

☞ NestJS Zero to Hero - Modern TypeScript Back-end Development

☞ The Complete Node.js Developer Course (3rd Edition)

☞ Complete Next.js with React & Node - Beautiful Portfolio App

☞ Angular & NodeJS - The MEAN Stack Guide

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Docker for Node.js Projects From a Docker Captain

☞ Intro To MySQL With Node.js - Learn To Use MySQL with Node!

☞ Node.js Absolute Beginners Guide - Learn Node From Scratch

node-js javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.