Why can't get notified when a key expired with the following code?
I want to use redis, and when a key is expired then notify me. Then i can do something.
var Redis = require('ioredis')
var sub = new Redis()
var pub = new Redis()
var subKey = '__keyevent@0__:del'
sub.subscribe(subKey, function () {
console.log('subscribe success !')
})
sub.on('message', function (channel, message) {
console.log(channel, message, '======')
})
var testKey = 'test'
setTimeout(function () {
pub.multi()
.set(testKey, 'test redis notify')
.expire(testKey, 5)
.exec(function (err) {
if (err) {
console.log(err, 'why err ?')
return
}
console.log('.....')
})
}, 2000)
You need server-side support for keyspace notification.
redis-cli config set notify-keyspace-events KEA
After set, you may run bellow command to check:
redis-cli config get notify-keyspace-events
If you got message like:
1) "notify-keyspace-events"
2) "AKE"
Then, you can run your code and get what you want.
Further more, pay attention to timing-of-expired-events.
pre-requisite : you need to enable key-space notification by entering the below line in redis.conf. or you can enable it temproraly as answered above by "sel-fish".
Now, the code inside your setTimeout block fire these events :
as you can see it actually never fire del event. So that is the reason you are not getting notification.
so you need to subscribe to keyevent@0:expired channel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With