Sunday, May 28, 2017

Zero MQ : implementation of Publisher/Subscriber model using node

Zero MQ is a very easy technology to implement various message passing technology. Here I am trying to implement one of most common pattern Publisher/Subscriber model  with  Node JS and Zero MQ .

In Publisher/Subscriber model , Publisher (server) publish a message , and number of client that can subscribe it to it.

Before starting to code , Plz go ahead and intall zmq in your machine . You can follow step by step command in the below github gist
https://gist.github.com/cdjhlee/b8e3c927a01b0948b42d

Next you need to install zmq node module in your machine. I have installed it "globally" .

Let now , begin our Publisher. Here in the below code our Publisher is constantly watching a file and send a message when it find that file has been change. Let assume the file name is "pub.txt".

const fs = require('fs'),
zmq = require('/usr/local/lib/node_modules/zmq'),
filename = 'pub.txt';
const pub = zmq.socket('pub');
//watch the change in the file.
//when you want to sned the message make change in pub.txt
fs.watch(filename, function() {
//message send to subscriber with cat
pub.send( [ 'cat' , JSON.stringify({
type: 'change',
file: filename,
time: Date.now()
})
]);
//message send to subscriber with dog
setTimeout( function () {
pub.send(['dog' ,JSON.stringify({
type: 'change',
file: filename,
time: Date.now()
})
]);
} , 10000)
});
pub.bind('tcp://*:3000', function() {
console.log("Publisher listening to port 3000");
});
Here I have added the fs.watch function that monitor the change in the above file and send message to all the connected client when there is change in file.So when ever u want to trigger a message all u need to make change in pub.txt file.

I have written 2 subscriber one that subscribe to cat and other to dog. Now when the server , send the message . The respective client capture the message and print it to console.




const zmq = require('/usr/local/lib/node_modules/zmq');
sub = zmq.socket('sub');
//subscribe to only cat topic
sub.subscribe("cat");
sub.on('message' , function(topic , data) {
let msg = JSON.parse(data),
date = new Date(msg.time);
console.log( topic + ' file has got change : ' + date);
});
sub.connect('tcp://localhost:3000');
view raw zmq_clent1.js hosted with ❤ by GitHub

const zmq = require('/usr/local/lib/node_modules/zmq');
sub = zmq.socket('sub');
sub.subscribe("dat");
sub.on('message' , function(topic , data) {
let msg = JSON.parse(data),
date = new Date(msg.time);
console.log( topic + ' file has got change ' + date);
});
sub.connect('tcp://localhost:3000');
~
view raw zmq_client2.js hosted with ❤ by GitHub

4 comments: