Implement RabbitMQ in Nodejs
Posted By : Ankit Uniyal | 28-Jun-2018
In this blog, we will cover how we can connect to RabbitMQ, publish
RabbitMQ is basically a message queue software through which we can exchange data between processes, applications and servers
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
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
We are using '
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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ankit Uniyal
Ankit has knowledge in Javascript, NodeJS, AngularJS and MongoDB also have experience in using AWS Services.