RabbitMQ — message broker for reliable async communication.
1const amqp = require("amqplib");23class MessageBroker {4 constructor(url) {5 this.url = url;6 this.connection = null;7 this.channel = null;8 }910 async connect() {11 this.connection = await amqp.connect(this.url);12 this.channel = await this.connection.createChannel();13 }1415 async publish(exchange, routingKey, message) {16 await this.channel.assertExchange(exchange, "direct", { durable: true });17 this.channel.publish(18 exchange,19 routingKey,20 Buffer.from(JSON.stringify(message)),21 { persistent: true }22 );23 }2425 async consume(exchange, routingKey, handler) {26 await this.channel.assertExchange(exchange, "direct", { durable: true });27 const q = await this.channel.assertQueue("", { exclusive: true });28 await this.channel.bindQueue(q.queue, exchange, routingKey);2930 this.channel.consume(q.queue, async (msg) => {31 try {32 await handler(JSON.parse(msg.content.toString()));33 this.channel.ack(msg);34 } catch (err) {35 this.channel.nack(msg, false, true);36 }37 });38 }39}4041// Usage42const broker = new MessageBroker("amqp://localhost");43await broker.connect();4445// Publish46await broker.publish("orders", "order.created", { id: 123 });4748// Consume49await broker.consume("orders", "order.created", async (msg) => {50 console.log("Order received:", msg);51});