如何使用节点接收Redis过期事件? [英] How to receive Redis expire events with node?
问题描述
我想监听来自 Redis 的 expire 事件.我已经在我的 redis.conf
上配置了 notify-keyspace-events "AKE"
,这是我在节点上的代码:
I want to listen the expire events from Redis.
I've configured on my redis.conf
the notify-keyspace-events "AKE"
and this is my code on node:
const redis = require('redis');
const client = redis.createClient();
const subscriber = redis.createClient();
const KEY_EXPIRING_TIME = 10; // seconds
client.setex('myKey', KEY_EXPIRING_TIME, 'myValue');
subscriber.on('message', function(channel, msg) {
console.log( `On ${channel} received ${msg} event`);
});
subscriber.subscribe('myKey', function (err) {
console.log('subscribed!');
});
我希望在 10 秒内看到事件被触发.setex 命令正常工作,10 秒后密钥不在数据库中,我在尝试捕获事件时遇到问题.
What I hope is to see in 10 seconds that the event is triggered. The setex command works correctly, in 10 seconds the key is not in the database, I have the problem when I try to capture the event.
我做错了什么?
推荐答案
实际上可以监听过期"类型 keyevent 通知 使用订阅的客户端到特定频道 ('__keyevent@db__:expired'
) 并监听其 message 事件.
It is in fact possible to listen to the "expired" type keyevent notification using a subscribed client to the specific channel ('__keyevent@db__:expired'
) and listening to its message event.
概念验证(工作:使用 NodeJS v.9.4.0 测试)
Proof-of-concept (working : tested with NodeJS v.9.4.0)
const redis = require('redis')
const CONF = {db:3}
var pub, sub
//.: Activate "notify-keyspace-events" for expired type events
pub = redis.createClient(CONF)
pub.send_command('config', ['set','notify-keyspace-events','Ex'], SubscribeExpired)
//.: Subscribe to the "notify-keyspace-events" channel used for expired type events
function SubscribeExpired(e,r){
sub = redis.createClient(CONF)
const expired_subKey = '__keyevent@'+CONF.db+'__:expired'
sub.subscribe(expired_subKey,function(){
console.log(' [i] Subscribed to "'+expired_subKey+'" event channel : '+r)
sub.on('message',function (chan,msg){console.log('[expired]',msg)})
TestKey()
})
}
//.: For example (create a key & set to expire in 10 seconds)
function TestKey(){
pub.set('testing','redis notify-keyspace-events : expired')
pub.expire('testing',10)
}
这篇关于如何使用节点接收Redis过期事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!