ganeshmani / cloudnweb-comments

This Repo is a comment section for my blog cloudnweb.dev
0 stars 0 forks source link

Implementing Redis Pub/Sub in Node.js Application #4

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

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.

https://cloudnweb.dev/2019/08/implementing-redis-pub-sub-in-node-js-application/

jovialcore commented 3 years ago

Thanks for the tutorial.. PLeasse where/how do you see the published messages

ihor-lev commented 1 year ago

Thanks for the tutorial. Just a small update from 2022.

server-pub.js

const express = require("express")
const redis = require("redis")
const publisher = redis.createClient();
const app = express()

publisher.connect();

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`)
})

server-sub1.js

const express = require("express")
const redis = require("redis")
const subscriber = redis.createClient()
const app = express()

subscriber.connect();

subscriber.subscribe("user-notify", (message) => {
    console.log('Received data : ' + message);
});

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

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

server-sub2.js

const express = require("express")
const redis = require("redis")
const subscriber = redis.createClient()
const app = express()

subscriber.connect();

subscriber.subscribe("user-notify", (message) => {
    console.log('Received data : ' + message);
});

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

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

Run in separate terminals and test

node server-pub.js
node server-sub1.js
node server-sub2.js

curl http://localhost:3005