Introduction to Node Redis PubSub
Node-Redis-PubSub is a powerful library that allows developers to implement pub/sub (publish/subscribe) messaging systems on top of Redis, a popular in-memory data structure store. This guide introduces the key concepts and provides comprehensive examples to help you get started with Node-Redis-PubSub.
Setting Up Node-Redis-PubSub
const NRP = require('node-redis-pubsub'); const config = { port: 6379, host: '127.0.0.1', scope: 'demo', }; const nrp = new NRP(config);
Publishing Messages
nrp.emit('event:message', { text: 'Hello, World!' });
Subscribing to Messages
nrp.on('event:message', (data) => { console.log(`Received data: ${JSON.stringify(data)}`); });
Unsubscribing from Events
const callback = (data) => { console.log(data); }; nrp.on('event:unsubscribe', callback); nrp.off('event:unsubscribe', callback);
Error Handling
nrp.on('error', (err) => { console.error('Redis PubSub error: ', err); });
Using Wildcards with Events
nrp.on('event:*', (data, channel) => { console.log(`Received data: ${JSON.stringify(data)} on channel: ${channel}`); });
Comprehensive App Example
App Initialization
const NRP = require('node-redis-pubsub'); const config = { port: 6379, host: '127.0.0.1', scope: 'myApp', }; const nrp = new NRP(config);
Publish Message
setInterval(() => { nrp.emit('app:heartbeat', { time: Date.now() }); }, 1000);
Subscribe to Events
nrp.on('app:heartbeat', (data) => { console.log(`Heartbeat at ${new Date(data.time)}`); }); nrp.on('app:error', (err) => { console.error(`App error: ${err}`); });
With Node-Redis-PubSub, you can easily build a variety of real-time applications such as chat apps, live notifications, or IoT data processing systems.
Explore the official documentation for more detailed usage and advanced features.
Hash: e3da3bd420d4cb8864c62705f40ee6f99b131ec1d5cf642ff7a72e255e7e4e7e