Welcome to the Comprehensive Guide to busmq
busmq is a powerful message queue system built on Redis, designed for real-time messaging and data transfer. This guide introduces the APIs provided by busmq, complete with examples to help you integrate them into your applications efficiently.
Connecting to busmq
First, establish a connection to the busmq server:
const busmq = require('busmq');
const redisHost = '127.0.0.1';
const redisPort = 6379;
const bus = busmq.create({
redis: { host: redisHost, port: redisPort }
});
bus.connect();
Creating and Listening to Queues
Create a queue and listen for incoming messages:
const queue = bus.queue('myQueue');
queue.on('message', (msg) => {
console.log('Received message:', msg);
});
queue.subscribe();
// Sending a message to the queue
queue.push('Hello, busmq!');
Using Pub/Sub
Implement a publish-subscribe pattern to broadcast messages to multiple clients:
const channel = bus.channel('myChannel');
channel.on('message', (msg, host) => {
console.log(`Message from ${host}:`, msg);
});
channel.subscribe();
// Publishing a message
channel.publish('This is a broadcast message');
Bus Listeners
Listen to events on the entire bus object:
bus.on('online', () => {
console.log('Bus is connected and ready');
});
bus.on('offline', () => {
console.log('Bus is disconnected');
});
Request-Reply Pattern
Implement a request-reply pattern:
const reqBus = bus.queue('requestQueue');
const repBus = bus.queue('replyQueue');
reqBus.on('message', (msg) => {
console.log('Request received:', msg);
// Respond to the request
repBus.push('Reply to: ' + msg);
});
reqBus.subscribe();
// Sending a request
reqBus.push('Hello, need a reply!');
App Example
Here’s a simple chat application that demonstrates these APIs in action:
const busmq = require('busmq');
const bus = busmq.create({ redis: { host: '127.0.0.1', port: 6379 } });
bus.connect();
const usersChannel = bus.channel('userMessages');
usersChannel.on('message', (msg) => {
console.log('Broadcasting message:', msg);
usersChannel.publish(msg); // Re-broadcast the received message to all clients
});
usersChannel.subscribe();
function sendMessage(user, msg) {
usersChannel.publish(`${user}: ${msg}`);
}
// Usage example
sendMessage('user1', 'Hello, everyone!');
Conclusion
busmq offers a versatile set of features for implementing robust messaging systems. With the examples provided, you can now start building real-time applications that leverage busmq’s capabilities.
Hash: 2b2ae00a8dbc7e19e6cd594d6064455f50ae59ae55210cd01aa1a1df68521487