Search This Blog

2023/04/20

Simple Rabbit MQ implementation in Node.js

 Provider App:


const express = require("express");
const app = express();
const PORT = process.env.PORT || 4001;

var channel, connection; //global variables
const amqp = require("amqplib");

app.use(express.json());

connectQueue()

app.get("/send-msg", (req, res) => {

// data to be sent
const data = {
title: "Six of Crows",
author: "Leigh Burdugo"
}
sendData(data); // pass the data to the function we defined
console.log("A message is sent to queue")
res.send("Message Sent"); //response to the API request

})

app.listen(PORT, () => console.log("Server running at port " + PORT));


async function sendData(data) {
// send data to queue
await channel.sendToQueue("MyDurableQueue",
Buffer.from(JSON.stringify(data)));

// close the channel and connection
await channel.close();
await connection.close();
}


async function connectQueue() {
try {
connection = await amqp.connect("amqp://admin:sangram@localhost:5672");
channel = await connection.createChannel()
await channel.assertQueue("MyDurableQueue")
} catch (error) {
console.log(error)
}
}


Client App:

const express = require("express");
const app = express();
const PORT = process.env.PORT || 4002;
app.use(express.json());
app.listen(PORT, () => console.log("Server running at port " + PORT));


const amqp = require("amqplib");
var channel, connection;
connectQueue() // call the connect function
async function connectQueue() {
try {
connection = await amqp.connect("amqp://admin:sangram@localhost:5672");
channel = await connection.createChannel()
await channel.assertQueue("MyDurableQueue")
channel.consume("MyDurableQueue", data => {
console.log(`${Buffer.from(data.content)}`);
channel.ack(data);
})
} catch (error) {
console.log(error);
}
}


You Need to install amqplib & express node packages.run both applications.

Here client will run on 4002 port & Provider will run on 4001 port.



Initiate Message using following API Hit from Browser or postman

http://localhost:4001/send-msg


When you hit above URL output on Provider node console is

Server running at port 4001
A message is sent to queue

and message on client node console is

Server running at port 4002
{"title":"Six of Crows","author":"Leigh Burdugo"}

and GET API Response is:
Message Sent

No comments:

Post a Comment