修改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);