redis發佈訂閱實現各種定時業務(優惠券過時,商品不支付自動撤單,自動收貨等)

修改redis配置文件
找到機器上redis配置文件conf/redis.conf,新增一行  notify-keyspace-events Exphp

最後的Ex表明 監聽失效的鍵值redis

 

修改後效果以下圖
函數

代碼效果:ui

redis.class.php類:(這裏避免命名衝突,故命名Redis2)this

 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.phpspa

 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.phpcode

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);
相關文章
相關標籤/搜索