0
0
RabbitmqHow-ToBeginner · 4 min read

How to Use RabbitMQ with Node.js: Simple Guide

To use RabbitMQ with Node.js, install the amqplib package to connect and communicate with RabbitMQ server. Use it to create channels, declare queues, and send or receive messages asynchronously.
📐

Syntax

This is the basic syntax to connect to RabbitMQ and send a message using amqplib in Node.js:

  • amqp.connect(url): Connects to RabbitMQ server.
  • connection.createChannel(): Creates a channel for communication.
  • channel.assertQueue(queueName): Declares a queue to send or receive messages.
  • channel.sendToQueue(queueName, Buffer.from(message)): Sends a message to the queue.
  • channel.consume(queueName, callback): Receives messages from the queue.
javascript
const amqp = require('amqplib');

async function sendMessage() {
  const connection = await amqp.connect('amqp://localhost');
  const channel = await connection.createChannel();
  const queue = 'task_queue';
  const msg = 'Hello RabbitMQ';

  await channel.assertQueue(queue, { durable: true });
  channel.sendToQueue(queue, Buffer.from(msg));

  console.log(" [x] Sent '%s'", msg);
  await channel.close();
  await connection.close();
}

sendMessage();
Output
[x] Sent 'Hello RabbitMQ'
💻

Example

This example shows how to send and receive messages using RabbitMQ in Node.js. It demonstrates connecting to RabbitMQ, declaring a queue, sending a message, and consuming messages asynchronously.

javascript
const amqp = require('amqplib');

async function send() {
  const connection = await amqp.connect('amqp://localhost');
  const channel = await connection.createChannel();
  const queue = 'hello';
  const msg = 'Hello World!';

  await channel.assertQueue(queue, { durable: false });
  channel.sendToQueue(queue, Buffer.from(msg));
  console.log(" [x] Sent '%s'", msg);

  setTimeout(() => {
    channel.close();
    connection.close();
  }, 500);
}

async function receive() {
  const connection = await amqp.connect('amqp://localhost');
  const channel = await connection.createChannel();
  const queue = 'hello';

  await channel.assertQueue(queue, { durable: false });
  console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", queue);

  channel.consume(queue, (msg) => {
    if (msg !== null) {
      console.log(" [x] Received %s", msg.content.toString());
      channel.ack(msg);
    }
  });
}

send();
receive();
Output
[x] Sent 'Hello World!' [*] Waiting for messages in hello. To exit press CTRL+C [x] Received Hello World!
⚠️

Common Pitfalls

Common mistakes when using RabbitMQ with Node.js include:

  • Not awaiting asynchronous calls, causing unexpected behavior.
  • Forgetting to acknowledge messages with channel.ack(), which can cause messages to be re-delivered.
  • Not closing connections and channels properly, leading to resource leaks.
  • Using non-buffered messages or wrong encoding.

Always handle errors and use try/catch blocks in async functions.

rabbitmq
/* Wrong: Not acknowledging message */
channel.consume(queue, (msg) => {
  console.log("Received %s", msg.content.toString());
  // Missing channel.ack(msg);
});

/* Right: Acknowledge message after processing */
channel.consume(queue, (msg) => {
  console.log("Received %s", msg.content.toString());
  channel.ack(msg);
});
📊

Quick Reference

Here is a quick summary of key RabbitMQ with Node.js commands:

CommandDescription
amqp.connect(url)Connect to RabbitMQ server
connection.createChannel()Create a channel for communication
channel.assertQueue(queueName, options)Declare a queue with options
channel.sendToQueue(queueName, Buffer.from(message))Send a message to the queue
channel.consume(queueName, callback)Receive messages from the queue
channel.ack(message)Acknowledge message processing
channel.close()Close the channel
connection.close()Close the connection

Key Takeaways

Use the amqplib package to connect Node.js with RabbitMQ easily.
Always create a channel and declare queues before sending or receiving messages.
Acknowledge messages with channel.ack() to prevent re-delivery.
Close channels and connections properly to free resources.
Handle asynchronous calls with async/await and try/catch for reliability.