修改redis配置文件
找到机器上redis配置文件conf/redis.conf,新增一行 notify-keyspace-events Ex
最后的Ex代表 监听失效的键值
修改后效果如下图
代码效果:
redis.class.php类:(这里避免命名冲突,故命名Redis2)
1 <?php 2 class Redis2 3 { 4 private $redis; 5 6 public function __construct($host = '127.0.0.1', $port = 6379) 7 { 8 $this->redis = new Redis(); 9 $this->redis->connect($host, $port); 10 } 11 12 public function setex($key, $time, $val) 13 { 14 return $this->redis->setex($key, $time, $val); 15 } 16 17 public function set($key, $val) 18 { 19 return $this->redis->set($key, $val); 20 } 21 22 public function get($key) 23 { 24 return $this->redis->get($key); 25 } 26 27 public function expire($key = null, $time = 0) 28 { 29 return $this->redis->expire($key, $time); 30 } 31 32 public function psubscribe($patterns = array(), $callback) 33 { 34 $this->redis->psubscribe($patterns, $callback); 35 } 36 37 public function setOption() 38 { 39 $this->redis->setOption(\Redis::OPT_READ_TIMEOUT, -1); 40 } 41 42 }
psubscribe.php
1 <?php 2 require_once './Redis.class.php'; 3 $redis = new \Redis2(); 4 // 解决Redis客户端订阅时候超时情况 5 $redis->psubscribe(array('__keyevent@0__:expired'), 'keyCallback'); 6 // 回调函数,这里写处理逻辑 7 function keyCallback($redis, $pattern, $chan, $msg) 8 { 9 echo "Pattern: $pattern\n"; 10 echo "Channel: $chan\n"; 11 echo "Payload: $msg\n\n"; 12 //keyCallback为订阅事件后的回调函数,这里写业务处理逻辑, 13 //比如前面提到的商品不支付自动撤单,这里就可以根据订单id,来实现自动撤单 14 }
index.php
1 <?php 2 require_once './Redis.class.php'; 3 $redis = new \Redis2(); 4 $order_id = 123; 5 //设置一个时间为10秒的redis值 6 $redis->setex('order_id',10,$order_id);