如何使用Node接收Redis过期事件?

15

我想监听 Redis 的过期事件。我已经在我的 redis.conf 文件中配置了 notify-keyspace-events "AKE",这是我的 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秒内该键不在数据库中。当我尝试捕捉事件时出现问题。

我做错了什么?


检查我的答案,它提供了一个没有额外模块/库和不需要松散的超时/间隔的解决方案。 ;) - EMX
4个回答

29

实际上,可以使用订阅客户端订阅特定频道('__keyevent@db__:expired')并监听其 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)
}

1
我能否监听特定键模式过期事件? - Hardik Mandankaa

7

不需要使用 setInterval / setTimeout 或额外的库

你可以从以下代码中获取每个过期的键(key)。

import { createClient } from "redis";

const pub=createClient({ url: process.env.REDIS_URL });
pub.connect();
pub.configSet("notify-keyspace-events", "Ex");

const sub=pub.duplicate();
sub.connect();

sub.subscribe("__keyevent@0__:expired", (key) => {
    console.log("key=> ", key)
})

注意:此代码已经测试过,适用于 redis@4.0.0


如何监听特定的密钥模式过期事件? - Eli Zatlawy
为什么我们需要复制Redis客户端来作为订阅者使用? - Eli Zatlawy

7

方案1:

使用setInterval函数定期检查值是否过期。我知道这不等同于监听事件,但它可以间接地实现目的。

下面的代码每5秒钟检查一次该值。

const redis = require('redis');
const client = redis.createClient();
const subscriber = redis.createClient();
const KEY_EXPIRING_TIME = 10; // seconds

var args = ['myKey', KEY_EXPIRING_TIME,  'myValue'];


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!');
});

setInterval(function() {  
  client.get('myKey', function(err, value) {
    if (err) {
      throw err;
    }
    if (value) {
      console.log('value:', value);
    }
    else {
      console.log('value is gone');
      process.exit();
    }
  });
}, 5e3);

方法2:

可以使用redis-notifier来监听事件。但是,安装此软件包需要 Python >= v2.5.0 && < 3.0.0

redis-notifier

var RedisNotifier = require('redis-notifier');

var eventNotifier = new RedisNotifier(redis, {
  redis : { host : '127.0.0.1', port : 6379 },
  expired : true,
  evicted : true,
  logLevel : 'DEBUG' //Defaults To INFO 
});

//Listen for event emission 
eventNotifier.on('message', function(pattern, channelPattern, emittedKey) {
  var channel = this.parseMessageChannel(channelPattern);
  switch(channel.key) {
    case 'expired':
        this._handleExpired(emittedKey);
      break;
    case "evicted":
      this._handleEvicted(emittedKey);
      break;
    default:
      logger.debug("Unrecognized Channel Type:" + channel.type);
  }
});

0
REDIS_CLIENT.sendCommand(['config', 'set', 'notify-keyspace-events', 'Ex']);


REDIS_CLIENT.subscribe("__keyevent@0__:expired", (err) => {         
    if (err) {
        console.error(err);
    } else {
        console.log('Subscribed to mychannel');
    }
 });

使用此代码段并授予所有必要的权限,您的代码将正常工作。

你如何监听特定的密钥模式过期事件? - Eli Zatlawy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接