如何通过node接收Redis过期事件?

xytpbqjk  于 2023-04-29  发布在  Redis
关注(0)|答案(4)|浏览(144)

我想听听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秒钟内密钥不在数据库中,我在尝试捕获事件时遇到了问题。
我做错了什么?

7rtdyuoh

7rtdyuoh1#

实际上,可以使用订阅的客户端监听特定通道('__keyevent@db__:expired')的“过期”类型keyevent notification,并监听其 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)
}
dbf7pr2w

dbf7pr2w2#

方法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);

方式二:-
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);
  }
});
cunj1qz1

cunj1qz13#

不需要setInterval / setTimeout或其他库

您可以从下面的代码中获取所有过期的密钥。

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测试

oaxa6hgo

oaxa6hgo4#

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

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

相关问题