0
0
RabbitmqHow-ToBeginner · 4 min read

How to Use amqplib in Node.js for RabbitMQ Messaging

Use amqplib in Node.js by first installing it with npm install amqplib. Then, create a connection to RabbitMQ, open a channel, and use that channel to send or receive messages with assertQueue, sendToQueue, and consume methods.
📐

Syntax

The basic steps to use amqplib are:

  • Connect: Use amqp.connect(url) to connect to RabbitMQ server.
  • Create Channel: Use connection.createChannel() to open a channel for communication.
  • Assert Queue: Use channel.assertQueue(queueName) to declare a queue.
  • Send Message: Use channel.sendToQueue(queueName, Buffer.from(message)) to send messages.
  • Consume Message: Use channel.consume(queueName, callback) to receive messages.
javascript
const amqp = require('amqplib');

async function run() {
  const connection = await amqp.connect('amqp://localhost');
  const channel = await connection.createChannel();
  await channel.assertQueue('myQueue');
  channel.sendToQueue('myQueue', Buffer.from('Hello World'));
  channel.consume('myQueue', msg => {
    if (msg !== null) {
      console.log(msg.content.toString());
      channel.ack(msg);
    }
  });
}

run();
💻

Example

This example shows how to connect to RabbitMQ, send a message to a queue, and receive it back.

javascript
const amqp = require('amqplib');

async function example() {
  try {
    const connection = await amqp.connect('amqp://localhost');
    const channel = await connection.createChannel();

    const queue = 'testQueue';
    await channel.assertQueue(queue, { durable: false });

    const message = 'Hello from amqplib!';
    channel.sendToQueue(queue, Buffer.from(message));
    console.log(`Sent: ${message}`);

    channel.consume(queue, msg => {
      if (msg !== null) {
        console.log(`Received: ${msg.content.toString()}`);
        channel.ack(msg);
        connection.close();
      }
    });
  } catch (error) {
    console.error('Error:', error);
  }
}

example();
Output
Sent: Hello from amqplib! Received: Hello from amqplib!
⚠️

Common Pitfalls

Common mistakes when using amqplib include:

  • Not awaiting asynchronous calls, causing unexpected behavior.
  • Forgetting to acknowledge messages with channel.ack(msg), which can cause messages to be re-delivered.
  • Not closing connections properly, leading to resource leaks.
  • Using sendToQueue without asserting the queue first.

Always use async/await and handle errors to avoid these issues.

javascript
/* Wrong way: Not awaiting connection and channel creation */
const amqp = require('amqplib');

const connection = amqp.connect('amqp://localhost'); // Missing await
const channel = connection.createChannel(); // Missing await

channel.assertQueue('queue'); // May fail because channel is a Promise
channel.sendToQueue('queue', Buffer.from('msg'));

/* Right way: Use async/await */
async function correct() {
  const connection = await amqp.connect('amqp://localhost');
  const channel = await connection.createChannel();
  await channel.assertQueue('queue');
  channel.sendToQueue('queue', Buffer.from('msg'));
}
correct();
📊

Quick Reference

MethodPurposeNotes
amqp.connect(url)Connect to RabbitMQ serverReturns a Promise with connection
connection.createChannel()Create a channel for messagingReturns a Promise with channel
channel.assertQueue(queueName)Declare a queueEnsures queue exists before sending/receiving
channel.sendToQueue(queueName, Buffer)Send message to queueMessage must be a Buffer
channel.consume(queueName, callback)Receive messages from queueCallback handles each message
channel.ack(msg)Acknowledge message processingPrevents message re-delivery

Key Takeaways

Always use async/await to handle amqplib's asynchronous methods.
Assert queues before sending or consuming messages to avoid errors.
Acknowledge messages after processing to prevent duplicates.
Close connections properly to free resources.
Use Buffer.from() to convert messages to the required format.