Logo
Published on

RabbitMQ - how to add it to NodeJS project?

Authors
  • avatar
    Name
    Kamil Cieplicki
    Twitter

What is RabbitMQ?

RabbitMQ is an open-source message broker software that allows applications to communicate with each other using a message queue. It is a widely-used software that implements the Advanced Message Queuing Protocol (AMQP) standard, which defines a protocol for message-oriented middleware.

Message-oriented middleware (MOM) is a type of software that allows applications to send and receive messages asynchronously. It enables applications to communicate with each other without being directly connected, allowing them to be developed and deployed independently.

RabbitMQ is designed to be lightweight, fast, and easy to use, making it an excellent choice for a wide range of applications. It is used in a variety of scenarios, including real-time messaging, work queues, and event-driven architectures.

In addition to the AMQP standard, RabbitMQ also supports other messaging protocols such as MQTT and STOMP. This makes it a versatile and flexible tool that can be used in a variety of environments.

How to add RabbitMQ to NodeJS project?

To add RabbitMQ to a JavaScript project, you will need to install the amqplib library, which provides a client for interacting with RabbitMQ from Node.js.

To install amqplib, you can use the following command:

npm install amqplib

Once amqplib is installed, you can use it to connect to a RabbitMQ server and perform various operations such as publishing messages, subscribing to queues, and setting up exchanges.

Here is an example of how you might use amqplib to publish a message to a queue in a RabbitMQ server:

const amqp = require('amqplib');

async function publishMessage() {
  // Connect to the RabbitMQ server
  const connection = await amqp.connect('amqp://localhost');

  // Create a channel
  const channel = await connection.createChannel();

  // Declare a queue
  const queue = 'my-queue';
  await channel.assertQueue(queue, { durable: true });

  // Publish a message to the queue
  const message = 'Hello, world!';
  channel.sendToQueue(queue, Buffer.from(message));

  console.log(`Published message: ${message}`);

  // Close the connection
  await connection.close();
}

publishMessage();

This example connects to a RabbitMQ server running on localhost, creates a channel, declares a queue, and publishes a message to the queue.

You can find more information about using amqplib and RabbitMQ in the library's documentation. https://www.rabbitmq.com/documentation.html