1. 程式人生 > >用PHP+Redis實現延遲任務,實現自動取消訂單

用PHP+Redis實現延遲任務,實現自動取消訂單

簡單定時任務解決方案:使用redis的keyspace notifications(鍵失效後通知事件) 需要注意此功能是在redis 2.8版本以後推出的,因此你伺服器上的reids最少要是2.8版本以上;

 

(A)業務場景:

1、當一個業務觸發以後需要啟動一個定時任務,在指定時間內再去執行一個任務(如自動取消訂單,自動完成訂單等功能)

2、redis的keyspace notifications 會在key失效後傳送一個事件,監聽此事件的的客戶端就可以收到通知

(B)服務準備:

1、修改reids配置檔案(redis.conf)【window系統配置檔案為:redis.windows.conf 】

redis預設不會開啟keyspace notifications,因為開啟後會對cpu有消耗

備註:E:keyevent事件,事件以__keyevent@<db>__為字首進行釋出;

x:過期事件,當某個鍵過期並刪除時會產生該事件;

原配置為:

notify-keyspace-events ""

更改 配置如下:

notify-keyspace-events "Ex"

儲存配置後,重啟Redis服務,使配置生效

[root@chokingwin etc]#
service redis-server restart /usr/local/redis/etc/redis.conf 
Stopping redis-server: [ OK ] 
Starting redis-server: [ OK ]

 

 

window系統重啟redis ,先切換到redis檔案目錄,然後關閉redis服務(redis-server --service-stop),再開啟(redis-server --service-start)

C)檔案程式碼:

phpredis實現訂閱Keyspace notification,可實現自動取消訂單,自動完成訂單。以下為測試例子

建立4個檔案,然後自行修改資料庫和redis配置引數

db.class.php

<?php
class mysql
{
    private $mysqli;
    private $result;
    /**
     * 資料庫連線
     * @param $config 配置陣列
     */

    public function connect()
    {
        $config=array(
            'host'=>'127.0.0.1',
            'username'=>'root',
            'password'=>'168168',
            'database'=>'test',
            'port'=>3306,
        );

        $host = $config['host'];    //主機地址
        $username = $config['username'];//使用者名稱
        $password = $config['password'];//密碼
        $database = $config['database'];//資料庫
        $port = $config['port'];    //埠號
        $this->mysqli = new mysqli($host, $username, $password, $database, $port);

    }
    /**
     * 資料查詢
     * @param $table 資料表
     * @param null $field 欄位
     * @param null $where 條件
     * @return mixed 查詢結果數目
     */
    public function select($table, $field = null, $where = null)
    {
        $sql = "SELECT * FROM `{$table}`";
        //echo $sql;exit;
        if (!empty($field)) {
            $field = '`' . implode('`,`', $field) . '`';
            $sql = str_replace('*', $field, $sql);
        }
        if (!empty($where)) {
            $sql = $sql . ' WHERE ' . $where;
        }


        $this->result = $this->mysqli->query($sql);

        return $this->result;
    }
    /**
     * @return mixed 獲取全部結果
     */
    public function fetchAll()
    {
        return $this->result->fetch_all(MYSQLI_ASSOC);
    }
    /**
     * 插入資料
     * @param $table 資料表
     * @param $data 資料陣列
     * @return mixed 插入ID
     */
    public function insert($table, $data)
    {
        foreach ($data as $key => $value) {
            $data[$key] = $this->mysqli->real_escape_string($value);
        }
        $keys = '`' . implode('`,`', array_keys($data)) . '`';
        $values = '\'' . implode("','", array_values($data)) . '\'';
        $sql = "INSERT INTO `{$table}`( {$keys} )VALUES( {$values} )";
        $this->mysqli->query($sql);
        return $this->mysqli->insert_id;
    }
    /**
     * 更新資料
     * @param $table 資料表
     * @param $data 資料陣列
     * @param $where 過濾條件
     * @return mixed 受影響記錄
     */
    public function update($table, $data, $where)
    {
        foreach ($data as $key => $value) {
            $data[$key] = $this->mysqli->real_escape_string($value);
        }
        $sets = array();
        foreach ($data as $key => $value) {
            $kstr = '`' . $key . '`';
            $vstr = '\'' . $value . '\'';
            array_push($sets, $kstr . '=' . $vstr);
        }
        $kav = implode(',', $sets);
        $sql = "UPDATE `{$table}` SET {$kav} WHERE {$where}";

        $this->mysqli->query($sql);
        return $this->mysqli->affected_rows;
    }
    /**
     * 刪除資料
     * @param $table 資料表
     * @param $where 過濾條件
     * @return mixed 受影響記錄
     */
    public function delete($table, $where)
    {
        $sql = "DELETE FROM `{$table}` WHERE {$where}";
        $this->mysqli->query($sql);
        return $this->mysqli->affected_rows;
    }
}

 

 

index.php

 1 <?php
 2 
 3 require_once 'Redis2.class.php';
 4 
 5 $redis = new \Redis2('127.0.0.1','6379','','15');
 6 $order_sn   = 'SN'.time().'T'.rand(10000000,99999999);
 7 
 8 $use_mysql = 1;         //是否使用資料庫,1使用,2不使用
 9 if($use_mysql == 1){
10    /*
11     *   //資料表
12     *   CREATE TABLE `order` (
13     *      `ordersn` varchar(255) NOT NULL DEFAULT '',
14     *      `status` varchar(255) NOT NULL DEFAULT '',
15     *      `createtime` varchar(255) NOT NULL DEFAULT '',
16     *      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
17     *       PRIMARY KEY (`id`)
18     *   ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8mb4;
19    */
20     require_once 'db.class.php';
21     $mysql      = new \mysql();
22     $mysql->connect();
23     $data       = ['ordersn'=>$order_sn,'status'=>0,'createtime'=>date('Y-m-d H:i:s',time())];
24     $mysql->insert('order',$data);
25 }
26 
27 $list = [$order_sn,$use_mysql];
28 $key = implode(':',$list);
29 
30 $redis->setex($key,3,'redis延遲任務');      //3秒後回撥
31 
32 
33 
34 $test_del = false;      //測試刪除快取後是否會有過期回撥。結果:沒有回撥
35 if($test_del == true){
36     //sleep(1);
37     $redis->delete($order_sn);
38 }
39 
40 echo $order_sn;
41 
42 
43 
44 /*
45  *   測試其他key會不會有回撥,結果:有回撥
46  *   $k = 'test';
47  *   $redis2->set($k,'100');
48  *   $redis2->expire($k,10);
49  *
50 */

 

 

psubscribe.php

 1 <?php
 2 ini_set('default_socket_timeout', -1);  //不超時
 3 require_once 'Redis2.class.php';
 4 $redis_db = '15';
 5 $redis = new \Redis2('127.0.0.1','6379','',$redis_db);
 6 // 解決Redis客戶端訂閱時候超時情況
 7 $redis->setOption();
 8 //當key過期的時候就看到通知,訂閱的key __keyevent@<db>__:expired 這個格式是固定的,db代表的是資料庫的編號,由於訂閱開啟之後這個庫的所有key過期時間都會被推送過來,所以最好單獨使用一個數據庫來進行隔離
 9 $redis->psubscribe(array('__keyevent@'.$redis_db.'__:expired'), 'keyCallback');
10 // 回撥函式,這裡寫處理邏輯
11 function keyCallback($redis, $pattern, $channel, $msg)
12 {
13     echo PHP_EOL;
14     echo "Pattern: $pattern\n";
15     echo "Channel: $channel\n";
16     echo "Payload: $msg\n\n";
17     $list = explode(':',$msg);
18 
19     $order_sn = isset($list[0])?$list[0]:'0';
20     $use_mysql = isset($list[1])?$list[1]:'0';
21 
22     if($use_mysql == 1){
23         require_once 'db.class.php';
24         $mysql = new \mysql();
25         $mysql->connect();
26         $where = "ordersn = '".$order_sn."'";
27         $mysql->select('order','',$where);
28         $finds=$mysql->fetchAll();
29         print_r($finds);
30         if(isset($finds[0]['status']) && $finds[0]['status']==0){
31             $data   = array('status' => 3);
32             $where  = " id = ".$finds[0]['id'];
33             $mysql->update('order',$data,$where);
34         }
35     }
36 
37 }
38 
39 
40 //或者
41 /*$redis->psubscribe(array('__keyevent@'.$redis_db.'__:expired'), function ($redis, $pattern, $channel, $msg){
42     echo PHP_EOL;
43     echo "Pattern: $pattern\n";
44     echo "Channel: $channel\n";
45     echo "Payload: $msg\n\n";
46     //................
47 });*/
48 
49  

 

Redis2.class.php

 1 <?php
 2 
 3 class Redis2
 4 {
 5     private $redis;
 6 
 7     public function __construct($host = '127.0.0.1', $port = '6379',$password = '',$db = '15')
 8     {
 9         $this->redis = new Redis();
10         $this->redis->connect($host, $port);    //連線Redis
11         $this->redis->auth($password);      //密碼驗證
12         $this->redis->select($db);    //選擇資料庫
13     }
14 
15     public function setex($key, $time, $val)
16     {
17         return $this->redis->setex($key, $time, $val);
18     }
19 
20     public function set($key, $val)
21     {
22         return $this->redis->set($key, $val);
23     }
24 
25     public function get($key)
26     {
27         return $this->redis->get($key);
28     }
29 
30     public function expire($key = null, $time = 0)
31     {
32         return $this->redis->expire($key, $time);
33     }
34 
35     public function psubscribe($patterns = array(), $callback)
36     {
37         $this->redis->psubscribe($patterns, $callback);
38     }
39 
40     public function setOption()
41     {
42         $this->redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
43     }
44 
45     public function lRange($key,$start,$end)
46     {
47         return $this->redis->lRange($key,$start,$end);
48     }
49 
50     public function lPush($key, $value1, $value2 = null, $valueN = null ){
51         return $this->redis->lPush($key, $value1, $value2 = null, $valueN = null );
52     }
53 
54     public function delete($key1, $key2 = null, $key3 = null)
55     {
56         return $this->redis->delete($key1, $key2 = null, $key3 = null);
57     }
58 
59 }

 

 

window系統測試方法:先在cmd命令介面執行psubscribe.php,然後網頁開啟index.php。

使監聽後臺始終執行(訂閱)

有個問題 做到這一步,利用 phpredis 擴充套件,成功在程式碼裡實現對過期 Key 的監聽,並在 psCallback()裡進行回撥處理。開頭提出的兩個需求已經實現。可是這裡有個問題:redis 在執行完訂閱操作後,終端進入阻塞狀態,需要一直掛在那。且此訂閱指令碼需要人為在命令列執行,不符合實際需求。

實際上,我們對過期監聽回撥的需求,是希望它像守護程序一樣,在後臺執行,當有過期事件的訊息時,觸發回撥函式。使監聽後臺始終執行 希望像守護程序一樣在後臺一樣,

我是這樣實現的。

Linux中有一個nohup命令。功能就是不掛斷地執行命令。同時nohup把指令碼程式的所有輸出,都放到當前目錄的nohup.out檔案中,如果檔案不可寫,則放到<使用者主目錄>/nohup.out 檔案中。那麼有了這個命令以後,不管我們終端視窗是否關閉,都能夠讓我們的php指令碼一直執行。

編寫psubscribe.php檔案:

 1 <?php
 2 #! /usr/bin/env php
 3 ini_set('default_socket_timeout', -1);  //不超時
 4 require_once 'Redis2.class.php';
 5 $redis_db = '15';
 6 $redis = new \Redis2('127.0.0.1','6379','',$redis_db);
 7 // 解決Redis客戶端訂閱時候超時情況
 8 $redis->setOption();
 9 //當key過期的時候就看到通知,訂閱的key __keyevent@<db>__:expired 這個格式是固定的,db代表的是資料庫的編號,由於訂閱開啟之後這個庫的所有key過期時間都會被推送過來,所以最好單獨使用一個數據庫來進行隔離
10 $redis->psubscribe(array('__keyevent@'.$redis_db.'__:expired'), 'keyCallback');
11 // 回撥函式,這裡寫處理邏輯
12 function keyCallback($redis, $pattern, $channel, $msg)
13 {
14     echo PHP_EOL;
15     echo "Pattern: $pattern\n";
16     echo "Channel: $channel\n";
17     echo "Payload: $msg\n\n";
18     $list = explode(':',$msg);
19 
20     $order_sn = isset($list[0])?$list[0]:'0';
21     $use_mysql = isset($list[1])?$list[1]:'0';
22 
23     if($use_mysql == 1){
24         require_once 'db.class.php';
25         $mysql = new \mysql();
26         $mysql->connect();
27         $where = "ordersn = '".$order_sn."'";
28         $mysql->select('order','',$where);
29         $finds=$mysql->fetchAll();
30         print_r($finds);
31         if(isset($finds[0]['status']) && $finds[0]['status']==0){
32             $data   = array('status' => 3);
33             $where  = " id = ".$finds[0]['id'];
34             $mysql->update('order',$data,$where);
35         }
36     }
37 
38 }
39 
40 
41 //或者
42 /*$redis->psubscribe(array('__keyevent@'.$redis_db.'__:expired'), function ($redis, $pattern, $channel, $msg){
43     echo PHP_EOL;
44     echo "Pattern: $pattern\n";
45     echo "Channel: $channel\n";
46     echo "Payload: $msg\n\n";
47     //................
48 });*/

 

 

注意:我們在開頭,申明 php 編譯器的路徑:

#! /usr/bin/env php

這是執行 php 指令碼所必須的。

然後,nohup 不掛起執行 psubscribe.php,注意 末尾的 &

[root@chokingwin HiGirl]# nohup ./psubscribe.php & 
[1] 4456 nohup: ignoring input and appending output to `nohup.out'

 

說明:指令碼確實已經在 4456 號程序上跑起來。

檢視下nohup.out cat 一下 nohuo.out,看下是否有過期輸出:

[root@chokingwin HiGirl]# cat nohup.out 
Pattern:__keyevent@0__:expired 
Channel: __keyevent@0__:expired 
Payload: name

 

執行index.php ,3秒後效果如上即成功

遇到問題:使用命令列模式開啟監控指令碼 ,一段時間後報錯 :Error while sending QUERY packet. PID=xxx

解決方法:由於等待訊息佇列是一個長連線,而等待回撥前有個資料庫連線,資料庫的wait_timeout=28800,所以只要下一條訊息離上一條訊息超過8小時,就會出現這個錯誤,把wait_timeout設定成10,並且捕獲異常,發現真實的報錯是 MySQL server has gone away ,
所以只要處理完所有業務邏輯後主動關閉資料庫連線,即資料庫連線主動close掉就可以解決問題

yii解決方法如下:

Yii::$app->db->close();

檢視程序方法:

 ps -aux|grep psubscribe.php

a:顯示所有程式
u:以使用者為主的格式來顯示
x:顯示所有程式,不以終端機來區分

檢視jobs程序ID:[ jobs -l ]命令

www@iZ232eoxo41Z:~/tinywan $ jobs -l
[1]-  1365 Stopped (tty output)    sudo nohup psubscribe.php > /dev/null 2>&1 
[2]+ 1370 Stopped (tty output) sudo nohup psubscribe.php > /dev/null 2>&1

終止後臺執行的程序方法:

kill -9  程序號

清空 nohup.out檔案方法:

cat /dev/null > nohup.out

我們在使用nohup的時候,一般都和&配合使用,但是在實際使用過程中,很多人後臺掛上程式就這樣不管了,其實這樣有可能在當前賬戶非正常退出或者結束的時候,命令還是自己結束了。

所以在使用nohup命令後臺執行命令之後,我們需要做以下操作:

1.先回車,退出nohup的提示。

2.然後執行exit正常退出當前賬戶。
3.然後再去連結終端。使得程式後臺正常執行。

我們應該每次都使用exit退出,而不應該每次在nohup執行成功後直接關閉終端。這樣才能保證命令一直在後臺運