Welcome folks,
Read about microservices/ event-driven architecture first.
link to the read article
So let's make a pub/sub program using RabbitMQ and Node.js
Before we started lets setup the project folder,
- Install RabbitMQ using https://www.rabbitmq.com/download.html
- Make a folder with name rbmq
- install amqplib using https://www.npmjs.com/package/amqplib
npm install amqplib --save
Now your package.json will look like this,
{
"name": "rbmq",
"version": "1.0.0",
"description": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node producer.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"amqplib": "^0.5.3"
}
}```
Now lets deep into codes,
Since its a producer-consumer programming model, lets create two consumers and a producer file.
Now your project folder will look like this;

If I make a queue with the name as 'tasks' then RabbitMQ will send the message to the corresponding subscribers which consume this 'tasks' queue.
producer program
var q = 'tasks';
var open = require('amqplib').connect('amqp://localhost');
// Publisher
open.then(function(conn) {
return conn.createChannel();
}).then(function(ch) {
return ch.assertQueue(q).then(function(ok) {
return ch.sendToQueue(q, Buffer.from('something to do'));
});
}).catch(console.warn);```
consumer program (paste the same in both consumer files)
var q = 'tasks';
var open = require('amqplib').connect('amqp://localhost');
// Consumer
open.then(function(conn) {
return conn.createChannel();
}).then(function(ch) {
return ch.assertQueue(q).then(function(ok) {
return ch.consume(q, function(msg) {
if (msg !== null) {
console.log(msg.content.toString());
ch.ack(msg);
}
});
});
}).catch(console.warn);
Run the producer and consumer program and now you can see consumers programs fetch the data from the queue and we can see the console on the terminal.
Github link: https://github.com/that-coder/RabbitMQ-example
Happy coding

