RabbitMQ Message Queues: Patterns and Implementation
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 Use durable queues Acknowledge messages Handle errors Monitor queues Use exchanges for routing Conclusion Implement reliable message queuing with RabbitMQ! 🐰