Approach 1:-
The setInterval function has to be used to check whether the value is expired periodically. I am aware that this is not equal to listening to events. However, it serves the purpose indirectly.
The below code checks the value for every 5 seconds.
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);
Approach 2:-
The redis-notifier
can be used to listen to the events. However, it requires Python >= v2.5.0 & < 3.0.0 in order to install this package.
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);
}
});