Sobes.tech
Junior — Middle

Have you used databases inside Docker containers?

sobes.tech AI

Answer from AI

Yes, I have experience with setting up and messaging using RabbitMQ in Node.js.

To work with RabbitMQ, the common library used is amqplib. Main steps:

  1. Connect to the RabbitMQ server.
  2. Create a channel.
  3. Declare a queue.
  4. Send messages to the queue.
  5. Receive 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 enables reliable message exchange between services with acknowledgments and fault tolerance.