方法一:-
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 & 才能安装此软件包。
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);
}
});