Loading

Node Pub-Sub Redis

A simple publish subscribe redis example with node.js

Barnabas Nomo | Fri, October 6th 2017


Redis is a fast, open source, in-memory key-value data structure store that comes with a set of versatile in-memory data structures which enable the easy creation of varieties of custom applications.

In this example, we'll subscribe to a channel on redis and try publishing to it. We'll have two files subscriber.js and publisher.js. We'll be listening for messages in subscriber.js. publisher.js will create a random string and publish to our redis store every 10seconds.

terminal

~$ mkdir redis-pub-sub-node && cd redis-pub-sub-node
~$ touch subscriber.js publisher.js
~$ npm init -y
~$ npm install --save redis

subscriber.js

var redis = require("redis")
  , subscriber = redis.createClient()
  , publisher = redis.createClient();
require('./publisher')(publisher);

subscriber.on("message", function(channel, message) {
  var report = {
    "message": message,
    "channel": channel
  }
  console.log(report)
});

subscriber.subscribe("myChannel");

publisher.js

module.exports = function (publisher) {
    setInterval(
        function () {
            publisher.publish("myChannel", makeid());
        }, 10000);
}


function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 10; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

now let's run our app.

~$ node subscriber.js
{ message: '9tNde0dgB2', channel: 'test' }
{ message: 'B3uaD8El2L', channel: 'test' }
{ message: '90hnmMLpVB', channel: 'test' }
{ message: 'yUdID9OGmF', channel: 'test' }
{ message: 'jxz7N8qbEJ', channel: 'test' }
{ message: '1vR7weCb80', channel: 'test' }