Skip to content

Instantly share code, notes, and snippets.

@JSoon
Created September 11, 2019 08:54
Show Gist options
  • Save JSoon/fa219cbc5aa4a554176f438ffa3566b2 to your computer and use it in GitHub Desktop.
Save JSoon/fa219cbc5aa4a554176f438ffa3566b2 to your computer and use it in GitHub Desktop.
ioredis实现Redis Keyspace Notifications
// 参考文献
// https://redis.io/topics/notifications
// https://medium.com/@micah1powell/using-redis-keyspace-notifications-for-a-reminder-service-with-node-c05047befec3
const Redis = require('ioredis');
//#region Redis测试
// subscriber
let RedisSubTester = new Redis({
port: 6379, // Redis port
host: "127.0.0.1", // Redis host
db: 0
});
// publisher
let RedisPubTester = new Redis({
port: 6379, // Redis port
host: "127.0.0.1", // Redis host
db: 0
});
// event handler
let RedisEventsHandler = new Redis({
port: 6379, // Redis port
host: "127.0.0.1", // Redis host
db: 0
});
RedisEventsHandler.on('ready', function () {
// https://redis.io/topics/notifications#configuration
RedisEventsHandler.config("SET", "notify-keyspace-events", "KEA");
RedisEventsHandler.setex('myKey', 5, 'Hello World');
// RedisEventsHandler.set('myKey', 'Hello World', 'Ex', 5);
});
let PubSub = {
publish(channel, message) {
RedisPubTester.publish(channel, message);
},
subscribe(channel) {
RedisSubTester.subscribe(channel);
},
psubscribe(channel) {
RedisSubTester.psubscribe(channel);
},
on(event, callback) {
RedisSubTester.on(event, (channel, message) => {
callback(channel, message);
});
}
};
// PubSub.subscribe("__keyevent@0__:expired"); // normal subscriber
PubSub.psubscribe("__key*__:*"); // pattern subscriber
PubSub.psubscribe("news");
PubSub.psubscribe("music");
PubSub.publish("news", "Hello world!");
PubSub.publish("music", "Hello again!");
PubSub.on("message", async (channel, message) => {
// Handle event
console.log(`channel: ${channel}, message: ${message}`);
});
PubSub.on("pmessage", async (pattern, channel, message) => {
// Handle event
console.log(`pattern: ${pattern}, channel: ${channel}, message: ${message}`);
});
//#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment