1.使用Redis过程中需要用到Key过期时回调一个函数。
const redis = require('redis')
const client = redis.createClient("6379", "localhost", { detect_buffers: true })
client.auth('123456')
console.log("设置过期数据!");
client.set('user:timeoutData', JSON.stringify({id:1,name:'allen'}), (err, res) => {
console.log(res);
})
client.expire("user:timeoutData", 20);
console.log("过期数据设置完毕");
client.send_command('config', ['set', 'notify-keyspace-events', 'Ex'], SubscribeExpired)
function SubscribeExpired(err, res) {
if (err) {
return
}
const expired_subKey = '__keyevent@0__:expired'; //订阅key过期事件
client.subscribe(expired_subKey, function () {
client.on('message', function (chan, msg) {
console.log("chan:" + chan)
//判断key做出相应的处理。
console.log("msg:" + msg)
});
})
}
2.问题:在多进程服务下,多个服务都会触发回调。
例:1.库存管理:用户提交订单30分钟内未支付库存回滚。
2.pm2 Cluster 启动多核服务(5个实例)。即5个实例同时监听了过期回调,数据一过期等于5次库存回滚。
如果有大佬能解决上述问题,请留言一下。谢谢!