Node如何接收Redis过期事件?

编程入门 行业动态 更新时间:2024-10-06 09:24:05

Node如何接收Redis过期<a href=https://www.elefans.com/category/jswz/34/1770959.html style=事件?"/>

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过期事件?

本文发布于:2024-05-30 10:04:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770376.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   Node   Redis

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!