Introduction to busmq
busmq is a messaging library for Node.js applications that supports various messaging patterns including queues, topics, and more. It’s designed for high performance, fault tolerance, and easy integration with multiple backends like Redis and MongoDB.
Setting Up busmq
const Bus = require('busmq');
const bus = Bus.create({ redis: ['redis://localhost:6379'] });
bus.connect();
Working with Queues
Queues are one of the fundamental features of busmq. Let’s see how to use them.
Creating a Queue
const queue = bus.queue('myQueue');
queue.attach();
Adding Messages to a Queue
queue.push('message1');
queue.push('message2');
Processing Messages from a Queue
queue.on('message', (message) => {
console.log('Received:', message);
});
queue.consume();
Working with Topics
Topics enable publishing messages to multiple subscribers.
Creating a Topic
const topic = bus.topic('myTopic');
topic.attach();
Publishing Messages to a Topic
topic.publish('Hello subscribers!');
Subscribing to a Topic
topic.on('message', (message) => {
console.log('Received:', message);
});
topic.subscribe();
Monitoring System Health
busmq provides built-in support for monitoring the health of your message buses.
Health Check Example
bus.on('online', () => {
console.log('Bus is online');
});
bus.on('offline', () => {
console.log('Bus is offline');
});
Example Application
Let’s create a simple application combining the features above.
Producer
const producerQueue = bus.queue('appQueue');
producerQueue.attach();
setInterval(() => {
const message = `Message at ${new Date().toISOString()}`;
producerQueue.push(message);
console.log('Produced:', message);
}, 1000);
Consumer
const consumerQueue = bus.queue('appQueue');
consumerQueue.attach();
consumerQueue.on('message', (message) => {
console.log('Consumed:', message);
});
consumerQueue.consume();
Now run both producer and consumer scripts to see the message flow.