Redis监听key失效事件
查找redis.conf在那个目录,命令:
find / -name redis.conf
进入目录,命令:
vi /usr/local/redis/etc/redis.conf
查找
notify-keyspace-events
,添加EX
重启redis服务,命令:
systemctl restart redis.service
redis配置页面 NewRedis.php
<?php class NewRedis { private $redis; public function __construct($host = '127.0.0.1', $port = 6379) { $this->redis = new \Redis(); $this->redis->connect($host, $port); } public function setex($key, $time, $val) { return $this->redis->setex($key, $time, $val); } public function set($key, $val) { return $this->redis->set($key, $val); } public function get($key) { return $this->redis->get($key); } public function expire($key = null, $time = 0) { return $this->redis->expire($key, $time); } public function psubscribe($patterns = array(), $callback) { $this->redis->psubscribe($patterns, $callback); } public function setOption() { $this->redis->setOption(\Redis::OPT_READ_TIMEOUT, -1); }
}
服务器开启监听
psubscribe.php
,Linux运行指令:php psubscribe.php
,页面代码如下:<?php require_once './NewRedis.php'; $redis = new NewRedis(); // 解决Redis客户端订阅时候超时情况 $redis->setOption(); $redis->psubscribe(array('__keyevent@0__:expired'), 'keyCallback'); // 回调函数,这里写处理逻辑 function keyCallback($redis, $pattern, $chan, $msg) { echo "Pattern: $pattern\n"; echo "Channel: $chan\n"; echo "Payload: $msg\n"; echo "订单号为:{$msg}的订单已失效"; }
客户端访问
index.php
,页面代码如下:<?php require_once './NewRedis.php'; $redis = new NewRedis(); $order_id = 123; $redis->setex('order_id1',20,$order_id);
特别感谢
参考博客:监听redis key失效触发回调事件
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: