具体文档可以查看: https://www.jianshu.com/p/1749339749cf
情况说明
当我支付宝创建订单后, 需要定时的把没有完成的订单给关闭, 这时候需要有个定时任务, 或者队列来完成, 不想安装兔子, 那就用本来就安装了的Redis来简单实现
步骤
1. 开启Redis通知事件
Centos中, 如果使用yum安装的话, 可以在 /etc/redis.conf
查看配置

可以在文件内搜索notify-keyspace-events
来找到, 并去除前面的注释

随后重启Redis
2. 安装ioredis
yarn add ioredis
3. 写代码
const Redis = require('ioredis')
const CONF = {
port: 6379,
host: "127.0.0.1",
db: 3
}
const redis = new Redis(CONF)
// 创建监听
redis.send_command('config', ['set', 'notify-keyspace-events', 'Ex'], subExpired)
// 存入一个四秒后会过期的键
redis.set('key', 'bar', 'EX', 4)
// 监听回调
function subExpired (err, res) {
// 这里需要创建一个新的Redis对象
// 因为 Connection in subscriber mode, only subscriber commands may be used
const sub = new Redis(CONF)
// 设置事件参数
const expired_subKey = `__keyevent@${CONF.db}__:expired`
sub.subscribe(expired_subKey, function () {
sub.on('message', function (info, msg) {
console.log(info, msg)
})
})
}
4.看结果

网友评论