最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Node如何接收Redis过期事件?

网站源码admin52浏览0评论

Node如何接收Redis过期事件?

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)
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论