在项目中,如果遇到订单失效、活动过期等功能时,除了使用定时轮询处理,还可以使用redis的key失效回调事件
1.修改redis配置
永久修改:
在redis.conf中开启notify-keyspace-events Ex,然后重启redis
临时修改:
在redis-cli客户端输入命令
127.0.0.1:6379> config set notify-keyspace-events Ex
2.编写php脚本test_script.php
ini_set('default_socket_timeout', -1);
$redis = new Redis();
$redis->pconnect('127.0.0.1',6379,0);
$redis->psubscribe(['__keyevent@0__:expired'], function ($redis, $pattern, $channel, $message) {
echo $message . PHP_EOL; // $message就是失效的key
});
php默认socket流超时时间为60s,改为-1不超时
连接redis由connect方法改为pconnect长连接,其中第三个参数为超时时间,0为不超时
__keyevent@0__中的0代表监听的数据库,*的话代表监听所有数据库
3.测试
开启脚本
php test_script.php
存储一个过期时间5s的key
$redis = new Redis();
$redis->connect('127.0.0.1',6379);
$redis->setex('order01', 5, 1);
等待5s后
php test.php
order01
脚本成功返回失效的键名
项目中可以在psubscribe的回调中写实际逻辑代码