node.js - 如何在 Redis key 过期时收到通知?

标签 node.js redis

为什么使用以下代码在 key 过期时无法收到通知?

我想使用redis,当key过期时通知我。那我可以做点什么。

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)

最佳答案

您需要服务器端对键空间通知的支持。

redis-cli config set notify-keyspace-events KEA

设置完成后,可以运行以下命令查看:

redis-cli config get notify-keyspace-events

如果您收到如下消息:

1) "notify-keyspace-events"
2) "AKE"

然后,您可以运行您的代码并获得您想要的结果。

更进一步,关注timing-of-expired-events .

关于node.js - 如何在 Redis key 过期时收到通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36615540/

相关文章:

redis - 当您在特定数据库上运行 `KEYS` 命令时,Redis 会锁定所有可用数据库吗?

在 Linux 上使用 Redis 编译 C 代码

redis - 使用 BLPOP 的 redis 作业队列

Spring Boot Reactive Redis 2 连接工厂导致健康检查失败

java - 带有 Long 类型键的 spring data redis zadd 不起作用

node.js - 部署到heroku后如何运行脚本

javascript - 保留对每个用户连接的套接字的引用

javascript - 无法通过 REST 客户端发送数组中的多个对象(Insomnia)

javascript - Nodejs Express 中的异步操作

node.js - 使用 vue.js 提高 JEST 测试性能