Implement RabbitMQ in Nodejs

Posted By : Ankit Uniyal | 28-Jun-2018

In this blog, we will cover how we can connect to RabbitMQ, publish message to message queue and consume message from message queue. But before moving forward, let us understand what is RabbitMQ and how it works.

 

RabbitMQ is basically a message queue software through which we can exchange data between processes, applications and servers.In Simple terms, it is a software where we can define queues and application can connect to the queue and publish message onto it.

 

Let's take an example where a pizza outlet allows the customer to order pizza online and each request is added as a message to the queue and consume by the receiving application. As each order is picked from message queue and after the deliver its status marked as done in database.

 

How to Install RabbitMQ in Ubuntu :

Below are the command which needs to be run one by one to install RabbitMQ in Ubuntu :

sudo apt-get install rabbitmq-server -q -y --force-yes


sudo rabbitmq-plugins enable rabbitmq_management


sudo rabbitmqctl add_user your_username yourpassword


sudo rabbitmqctl set_user_tags your_username administrator


sudo rabbitmqctl set_permissions your_username ".*" ".*" ".*"


sudo service rabbitmq-server restart

 

How to set up connection to RabbitMQ and consume message from Message queue using Nodejs :

We are using 'amqlib' npm module.

  var amqp = require('amqplib/callback_api');
  var amqpConn = null;
  amqp.connect('amqp://localhost', function(err, conn) {
      conn.createChannel(function(err, ch) {
          ch.assertQueue(queueName, {
              durable: true
          });
          console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", queueName);
          ch.consume(configurationHolder.config.queueName, function(msg) {
              console.log(" [x] Received %s", msg.content.toString());
              Promise.delay(500);
              conn.close();
              return msg.content.toString();
          }, {
              noAck: true
          });
      });
  });       
        

Next, how we can publish message to RabbitMQ message queue :

var amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost', function(err, conn) {
    conn.createChannel(function(err, ch) {
        var msg = 'Hello World!';
        ch.assertQueue(queueName, {
            durable: false
        });
        ch.sendToQueue(q, new Buffer(msg));
        console.log(" [x] Sent %s", msg);
    });
    Promise.delay(500);
    conn.close();
});       
        

Thanks.

About Author

Author Image
Ankit Uniyal

Ankit has knowledge in Javascript, NodeJS, AngularJS and MongoDB also have experience in using AWS Services.

Request for Proposal

Name is required

Comment is required

Sending message..