php监听redis中的key过期回调处理
php监听redis中的key过期回调处理
首先要开启redis配置
原配置
notify-keyspace-events ""
更改为
notify-keyspace-events "Ex"
这是因为redis默认不会开启keyspace notifications,因为开启后会对cpu有消耗
[root@localhost rs]# whereis redis
redis: /etc/redis.conf
[root@localhost rs]# sudo vim /etc/redis.conf
重启redis
[root@localhost rs]# systemctl restart redis
过期事件订阅
psubscribe.php
<?php
/*************************************************************************
* File Name: psubscribe.php
* Author: RS
* Created Time: 2023/4/13 11:33
* Desc:php监听redis中的key过期回调处理
************************************************************************/
ini_set('default_socket_timeout', -1); //php配置设置不超时
$redis = new Redis();
$redis->connect("127.0.0.1", 6379);
$redis->select(0);
$redis_db = 0; //local配置中的 dbN
$redis->setOption(Redis::OPT_READ_TIMEOUT, -1); //redis方式设置不超时,推荐
$redis->psubscribe(array('__keyevent@' . $redis_db . '__:expired'), function ($redis, $pattern, $chan, $msg){
echo "Pattern: $pattern\n";
echo "Channel: $chan\n";
echo "Payload: $msg\n\n";
});
举个例子
test_setx_expire.php
<?php
/*************************************************************************
* File Name: test_setx_expire_key.php
* Author: shijie.zheng
* Created Time: 2023/4/13 14:24
* Desc:
************************************************************************/
$redis = new Redis();
$redis->connect("127.0.0.1", 6379);
$redis->select( 0 );
$key = "cs";
$redis->set($key, time(), array('NX', 'EX' => 3));
[root@localhost rs]# sudo php psubscribe.php
Pattern: __keyevent@0__:expired
Channel: __keyevent@0__:expired
Payload: cs
[root@localhost rs]# sudo php test_setx_expire.php
检查key是否过期
check_key_ttl.php
redis = new Redis();
$redis->connect("127.0.0.1", 6379);
$redis->select( 0 );
$key = "cs";
$ttl = $redis->ttl($key);
if ($ttl == -1) {
echo "key 不存在或没有设置过期时间";
} else {
echo "key $key 过期时间剩余 $ttl 秒";
}