监听Redis列表中的更改

cetgtptt  于 2023-11-16  发布在  Redis
关注(0)|答案(1)|浏览(166)

我想写一个函数,不断监听redis列表中的变化(通常是当元素被推送到列表中时),并在列表不为空时弹出它的元素。然后它将对弹出的元素执行一个函数。我应该如何实现这一点?

xpcnnkqh

xpcnnkqh1#

你可以使用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);
        });
    })
})()

字符串
notify-keyspace-events配置的完整列表在这里

K     Keyspace events, published with __keyspace@<db>__ prefix.
E     Keyevent events, published with __keyevent@<db>__ prefix.
g     Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
$     String commands
l     List commands
s     Set commands
h     Hash commands
z     Sorted set commands
t     Stream commands
d     Module key type events
x     Expired events (events generated every time a key expires)
e     Evicted events (events generated when a key is evicted for maxmemory)
m     Key miss events (events generated when a key that doesn't exist is accessed)
n     New key events (Note: not included in the 'A' class)
A     Alias for "g$lshztxed", so that the "AKE" string means all the events except "m" and "n".

相关问题