node.jsredis

How to get notified when a redis key expired?


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)

Solution

  • 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.