RabbitMQ enables reliable message queuing. Here’s how to use it effectively.

Basic Setup

Producer

const amqp = require('amqplib');

async function sendMessage() {
    const connection = await amqp.connect('amqp://localhost');
    const channel = await connection.createChannel();
    
    const queue = 'tasks';
    const message = 'Hello RabbitMQ!';
    
    await channel.assertQueue(queue, { durable: true });
    channel.sendToQueue(queue, Buffer.from(message), {
        persistent: true
    });
    
    console.log("Sent:", message);
    await channel.close();
    await connection.close();
}

Consumer

async function receiveMessage() {
    const connection = await amqp.connect('amqp://localhost');
    const channel = await connection.createChannel();
    
    const queue = 'tasks';
    await channel.assertQueue(queue, { durable: true });
    
    channel.consume(queue, (msg) => {
        if (msg) {
            console.log("Received:", msg.content.toString());
            channel.ack(msg);
        }
    });
}

Patterns

Work Queues

// Distribute tasks among workers
channel.prefetch(1); // Fair dispatch

Pub/Sub

// Exchange for broadcasting
await channel.assertExchange('logs', 'fanout', { durable: false });
channel.publish('logs', '', Buffer.from(message));

Best Practices

  1. Use durable queues
  2. Acknowledge messages
  3. Handle errors
  4. Monitor queues
  5. Use exchanges for routing

Conclusion

Implement reliable message queuing with RabbitMQ! 🐰