// 参考文献 // 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