收听Redis列表中的更改

时间:2019-11-03 17:50:33

标签: redis listener

我想编写一个函数,该函数不断侦听redis列表中的更改(通常在元素被推送到列表时),并在列表不为空时弹出其元素。然后它将对弹出的元素执行一个功能。我应该如何实施呢?

1 个答案:

答案 0 :(得分:0)

您可以为此使用notify-keyspace-events

使用Node.js的示例,但其他语言的想法相似。

const Redis = require('ioredis')
const redis = new Redis()

;(async function () {
    redis.on('ready', () => {
        console.log('ready');

        redis.config('set', 'notify-keyspace-events', 'KEl')
        // KEl => see https://redis.io/topics/notifications to understand the configuration
        // l is meant we are interested in list event

        redis.psubscribe(['__key*__:*'])

        redis.on('pmessage', function(pattern, channel, message) {
            console.log('got %s', message);
        });
    })
})()

示例输出

enter image description here

相关问题