事件?"/>
Node如何接收Redis过期事件?
我想听Redis的过期事件。 我已经在我的
redis.conf
上配置了 notify-keyspace-events "AKE"
,这是我在节点上的代码:
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 秒后密钥不在数据库中,我在尝试捕获事件时遇到了问题。
我做错了什么?
回答如下:实际上可以使用订阅客户端到特定频道('__keyevent@db__:expired'
)来收听“过期”类型的
keyevent通知并收听其message事件。
不需要 setInterval / setTimeout 或其他库
概念验证(工作:使用 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)
}
更多推荐
Node如何接收Redis过期事件?
发布评论