Sobes.tech
Junior — Middle

Do you have experience configuring and transmitting messages using RabbitMQ?

sobes.tech AI

Answer from AI

Yes, I have experience configuring and transmitting messages using RabbitMQ in Node.js.

For working with RabbitMQ, the amqplib library is usually used. The main steps are:

  1. Connecting to the RabbitMQ server.
  2. Creating a channel.
  3. Declaring a queue.
  4. Sending messages to the queue.
  5. Receiving messages from the queue.

Example of sending and receiving messages:

const amqp = require('amqplib');

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

  await channel.assertQueue(queue, { durable: true });
  const msg = 'Hello RabbitMQ!';

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

  setTimeout(() => {
    connection.close();
    process.exit(0);
  }, 500);
}

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

  await channel.assertQueue(queue, { durable: true });
  channel.prefetch(1);

  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);
    }
  });
}

// Run functions as needed
// sendMessage();
// receiveMessage();

Thus, RabbitMQ allows organizing reliable message exchange between services with support for acknowledgments and fault tolerance.