import Redis from 'ioredis';
const subscribeChannel = new Redis({
host: 'localhost',
port: '6379',
db: 0,
});
const publishChannel = new Redis({
host: 'localhost',
port: '6379',
db: 0,
});
function set(channel, key, value, seconds){
channel.set(key, value);
// use shadowkey to access the value field on the expire event message
channel.set(`${key}:${value}`, '');
// set expire time on shadowkey
channel.expire(`${key}:${value}`, seconds);
}
publishChannel.on('ready', () => {
// configure keyspaces event and specify expiring events with "Ex"
publishChannel.config("SET", "notify-keyspace-events", "Ex");
// subscribe to the
subscribeChannel.subscribe("__keyevent@0__:expired");
// listen for expiring event messages
subscribeChannel.on('message', async(channel, message) => {
// retrieve key and value from shadowkey
const [key, value] = message.split(":");
// store value in the main storage
db.insert(value);
// delete actual value from the redis store
publishChannel.del(key);
});
// set "value" with "key" and set it to expire after 10 seconds
set(publishChannel, "key", "value", 10);
});
1条答案
按热度按时间ru9i0ody1#
你可以使用keyspace事件来监听密钥过期事件,你需要两个不同的通道,一个用于发布事件(主通道),另一个用于监听过期事件,Redis的默认行为是只返回过期事件消息中过期元素的密钥,解决方法可以在here中找到,下面是使用该解决方法的简单实现: