如何通过节点接收Redis到期事件?

时间:2017-02-03 15:45:27

标签: node.js redis ttl

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

我做错了什么?

2 个答案:

答案 0 :(得分:17)

实际上可以听到过期的"过期"使用订阅的客户端键入keyevent notification到特定频道('__keyevent@db__:expired')并收听其消息事件。

不需要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 :(得分:6)

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