Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get notified when a redis key expired?

Tags:

node.js

redis

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)
like image 262
AsherTan Avatar asked Dec 19 '22 17:12

AsherTan


2 Answers

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.

like image 108
sel-fish Avatar answered Dec 31 '22 18:12

sel-fish


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 :

  1. keyspace@0:test ======
  2. keyevent@0:set ======
  3. keyspace@0:test ======
  4. keyevent@0:expire ======
  5. keyspace@0:test ======
  6. keyevent@0:expired ======

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.

like image 43
anuj kumar jha Avatar answered Dec 31 '22 18:12

anuj kumar jha