Simple guide to use RabbitMQ with NODEJS

vishal rana
4 min readJan 12, 2022

--

Welcome to my blog. In this blog, I’ll try to explain the working of rabbitMQ with nodeJS in short and simple way possible.

PREREQUISITES

  • Should have NODEJS installed on your system. if not, then you can download from here.
  • Should have NPM/YARN installed, which we are going to use to import our packages.
  • Should have RabbitMQ installed on your system. if not then you can download from here.

Once we have all the prerequisites, let’s start with introducing you to the working process.

A little overview of RABBITMQ

In simple words, RabbitMQ is a queuing service that is being used to send and receive messages according to the requirement. There is a producer that publish the message , a consumer that is receiving the message and a queue that hold the message. It is as simple as that, no need to complicate things.

First we need to install “amqplib” package so that we can communicate with rabbitmq. Before that , make sure you have rabbitMQ working in your local. You can check that by simple visiting http://localhost:15672/

The default login credentials are username = “guest” and password = “guest”, if you are running the queue with default settings.

Once you are in, you’ll see something like this:

Now, you have rabbitMQ working. let’s install the package “amqplib” :

USING NPM

npm install --save amqplib

USING YARN

yarn add amqplib

Once you are done, let’s jump to the code.

So to make it work, we need a producer that will keep on adding messages to our queue and we need a consumer to read data from our queue.

create a ``producer.js`` file that will handle code of producer setup and it will keep on publishing the message.

const amqplib = require(“amqplib”);
const randomString = require("randomstring");
const defaultConnectionString = "amqp://localhost";
const queueName = "test";
// create a function to initiate the connection
const createConnection = async()=>{
return amqplib.connect(defaultConnectionString)
};
// Function to start sending random messagesconst sendMessages = async () => {const connection = await createConnection(); // making a connection to the queueconst channel = await connection.createChannel(); //create channelawait channel.assertQueue(queueName); //validating queueconst message = randomString.generate();channel.sendToQueue(queueName, Buffer.from(message)); // we need to send data as a buffer};sendMessages();

In the above code, we have used another package called “randomstring”, just to create random string for our message every time.

You can run the above file using:

node producer.js

It will create the connection to the queue and send the message to the queue. we have create a channel as well for the medium of communication.

Now let’s create a consumer file to recieve the message that the producer just sent to the queue.

“consumer.js”

const amqplib = require("amqplib");const defaultConnectionString = "amqp://localhost";const queueName = "test_queue";// create a function to initiate the connectionconst createConnection = async () => {return amqplib.connect(defaultConnectionString);};
// Function to start receiving messagesconst receiveMessages = async () => {const connection = await createConnection(); // making a connection to the queueconst channel = await connection.createChannel(); // creating a channel to communicateawait channel.assertQueue(queueName); // queue validity
channel.consume(queueName, (msg)=>{const receivedMsg = msg.content.toString();console.log({receivedMsg})});};receiveMessages();

Most of the code is same in consumer file, like making a connection, creating a channel, validating the queue. The extra thing is we are calling the consume function on the channel with the queue name to let the rabbitmq know that we need messages that are in this queue so start sending us there messages.

Here we have covered basics of how the producer and consumer works in a queue.

Now, here are some few things that might help you in some ways.

Let’s suppose we need one message at a time and until we finish with that message , we don’t want next message. Then we have to use the prefetch function on the channel, like

channel.prefetch(1) // this will give you 1 message at a time

By default, the messages are acknowledged automatically, that means they will be removed from the queue when processed.

// Function to start receiving messagesconst receiveMessages = async () => {const connection = await createConnection(); // making a connection to the queueconst channel = await connection.createChannel(); // creating a channel to communicateawait channel.assertQueue(queueName); // queue validitychannel.prefetch(1)channel.consume(queueName, (msg)=>{const receivedMsg = msg.content.toString();console.log({receivedMsg})// manual acknowledging the messageschannel.ack(msg)},{noAck: false});};

The above code will do that job for you, Now you shall received the messages one after another.

Here we are , you have successfully learnt how to use a rabbitMQ service using nodeJS.

Happy Reading…

--

--

No responses yet