Home  >  Article  >  Backend Development  >  Use PHP+Redis to implement delayed tasks and automatically cancel orders (detailed tutorial)

Use PHP+Redis to implement delayed tasks and automatically cancel orders (detailed tutorial)

PHPz
PHPzforward
2019-11-20 18:03:222944browse

Simple scheduled task solution: use keyspace notifications of redis (notification event after key failure). Please note that this feature was launched after redis version 2.8, so the reids on your server must be at least version 2.8 or above;

(A) Business scenario:

1. When a business is triggered, a scheduled task needs to be started, and another task must be executed within the specified time (such as automatic cancellation of orders, automatic completion Orders and other functions)

2. Redis’s keyspace notifications will send an event after the key expires, and the client that listens to this event can receive the notification

(B) Service Preparation:

1. Modify the reids configuration file (redis.conf) [window system configuration file is: redis.windows.conf]

redis will not enable keyspace notifications by default, because After being turned on, it will consume the CPU

Remarks: E: keyevent event, the event is published with __keyevent@909dafdfb3cc5ae0f4811767ed936791__ as the prefix;

x: Expired event, when a certain This event will occur when the key expires and is deleted;

The original configuration is:

notify-keyspace-events ""

Change the configuration as follows:

notify-keyspace-events "Ex"

After saving the configuration, restart the Redis service to make the configuration take effect

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

Restart redis in the window system, first switch to the redis file directory, and then close the redis service (redis-server --service-stop), then open (redis-server --service-start)

##C) File code:

phpredis implements subscription to Keyspace notification, which can automatically cancel orders and automatically complete orders. The following is a test example

Create 4 files, and then modify the database and redis configuration parameters yourself

db.class.php

33186afcce9d7ca96fe1e723da162548'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 = '//m.sbmmt.com/m/faq/\'' . implode("','", array_values($data)) . '//m.sbmmt.com/m/faq/\'';        $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 = '//m.sbmmt.com/m/faq/\'' . $value . '//m.sbmmt.com/m/faq/\'';            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

<?php

require_once &#39;Redis2.class.php&#39;;

$redis = new \Redis2(&#39;127.0.0.1&#39;,&#39;6379&#39;,&#39;&#39;,&#39;15&#39;);
$order_sn   = &#39;SN&#39;.time().&#39;T&#39;.rand(10000000,99999999);

$use_mysql = 1;         //是否使用数据库,1使用,2不使用
if($use_mysql == 1){
   /*
    *   //数据表
    *   CREATE TABLE `order` (
    *      `ordersn` varchar(255) NOT NULL DEFAULT &#39;&#39;,
    *      `status` varchar(255) NOT NULL DEFAULT &#39;&#39;,
    *      `createtime` varchar(255) NOT NULL DEFAULT &#39;&#39;,
    *      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    *       PRIMARY KEY (`id`)
    *   ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8mb4;
   */
    require_once &#39;db.class.php&#39;;
    $mysql      = new \mysql();
    $mysql->connect();
    $data       = [&#39;ordersn&#39;=>$order_sn,&#39;status&#39;=>0,&#39;createtime&#39;=>date(&#39;Y-m-d H:i:s&#39;,time())];
    $mysql->insert(&#39;order&#39;,$data);
}

$list = [$order_sn,$use_mysql];
$key = implode(&#39;:&#39;,$list);

$redis->setex($key,3,&#39;redis延迟任务&#39;);      //3秒后回调



$test_del = false;      //测试删除缓存后是否会有过期回调。结果:没有回调
if($test_del == true){
    //sleep(1);
    $redis->delete($order_sn);
}

echo $order_sn;



/*
 *   测试其他key会不会有回调,结果:有回调
 *   $k = &#39;test&#39;;
 *   $redis2->set($k,&#39;100&#39;);
 *   $redis2->expire($k,10);
 *
*/

psubscribe.php

<?php
ini_set(&#39;default_socket_timeout&#39;, -1);  //不超时
require_once &#39;Redis2.class.php&#39;;
$redis_db = &#39;15&#39;;
$redis = new \Redis2(&#39;127.0.0.1&#39;,&#39;6379&#39;,&#39;&#39;,$redis_db);
// 解决Redis客户端订阅时候超时情况
$redis->setOption();
//当key过期的时候就看到通知,订阅的key __keyevent@<db>__:expired 这个格式是固定的,db代表的是数据库的编号,由于订阅开启之后这个库的所有key过期时间都会被推送过来,所以最好单独使用一个数据库来进行隔离
$redis->psubscribe(array(&#39;__keyevent@&#39;.$redis_db.&#39;__:expired&#39;), &#39;keyCallback&#39;);
// 回调函数,这里写处理逻辑
function keyCallback($redis, $pattern, $channel, $msg)
{
    echo PHP_EOL;
    echo "Pattern: $pattern\n";
    echo "Channel: $channel\n";
    echo "Payload: $msg\n\n";
    $list = explode(&#39;:&#39;,$msg);

    $order_sn = isset($list[0])?$list[0]:&#39;0&#39;;
    $use_mysql = isset($list[1])?$list[1]:&#39;0&#39;;

    if($use_mysql == 1){
        require_once &#39;db.class.php&#39;;
        $mysql = new \mysql();
        $mysql->connect();
        $where = "ordersn = &#39;".$order_sn."&#39;";
        $mysql->select(&#39;order&#39;,&#39;&#39;,$where);
        $finds=$mysql->fetchAll();
        print_r($finds);
        if(isset($finds[0][&#39;status&#39;]) && $finds[0][&#39;status&#39;]==0){
            $data   = array(&#39;status&#39; => 3);
            $where  = " id = ".$finds[0][&#39;id&#39;];
            $mysql->update(&#39;order&#39;,$data,$where);
        }
    }

}


//或者
/*$redis->psubscribe(array(&#39;__keyevent@&#39;.$redis_db.&#39;__:expired&#39;), function ($redis, $pattern, $channel, $msg){
    echo PHP_EOL;
    echo "Pattern: $pattern\n";
    echo "Channel: $channel\n";
    echo "Payload: $msg\n\n";
    //................
});*/

Redis2.class.php

<?php

class Redis2
{
    private $redis;

    public function __construct($host = &#39;127.0.0.1&#39;, $port = &#39;6379&#39;,$password = &#39;&#39;,$db = &#39;15&#39;)
    {
        $this->redis = new Redis();
        $this->redis->connect($host, $port);    //连接Redis
        $this->redis->auth($password);      //密码验证
        $this->redis->select($db);    //选择数据库
    }

    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);
    }

    public function lRange($key,$start,$end)
    {
        return $this->redis->lRange($key,$start,$end);
    }

    public function lPush($key, $value1, $value2 = null, $valueN = null ){
        return $this->redis->lPush($key, $value1, $value2 = null, $valueN = null );
    }

    public function delete($key1, $key2 = null, $key3 = null)
    {
        return $this->redis->delete($key1, $key2 = null, $key3 = null);
    }

}

Window system test method: first run psubscribe.php in the cmd command interface, Then the web page opens index.php.

Make the monitoring background always run (subscription)

There is a problem to achieve this step. Using the phpredis extension, the monitoring of expired Keys was successfully implemented in the code and carried out in psCallback(). Callback handling. The two requirements raised at the beginning have been met. But there is a problem here: after redis performs the subscription operation, the terminal enters the blocking state and needs to hang there all the time. And this subscription script needs to be executed manually on the command line, which does not meet actual needs.

Actually, our requirement for the expiration listening callback is that we want it to run in the background like a daemon process, and trigger the callback function when there is news about an expiration event. Make the listening background always run. I hope it will be in the background like a daemon process.

This is how I implemented it.

There is a nohup command in Linux. The function is to run commands without hanging up. At the same time, nohup puts all the output of the script program into the nohup.out file in the current directory. If the file is not writable, it puts it into the 76d2719e5e5cbb441215b246f446deb8/nohup.out file. So with this command, our php script can always run regardless of whether our terminal window is closed or not.

Write the psubscribe.php file:

<?php
#! /usr/bin/env php
ini_set(&#39;default_socket_timeout&#39;, -1);  //不超时
require_once &#39;Redis2.class.php&#39;;
$redis_db = &#39;15&#39;;
$redis = new \Redis2(&#39;127.0.0.1&#39;,&#39;6379&#39;,&#39;&#39;,$redis_db);
// 解决Redis客户端订阅时候超时情况
$redis->setOption();
//当key过期的时候就看到通知,订阅的key __keyevent@<db>__:expired 这个格式是固定的,db代表的是数据库的编号,由于订阅开启之后这个库的所有key过期时间都会被推送过来,所以最好单独使用一个数据库来进行隔离
$redis->psubscribe(array(&#39;__keyevent@&#39;.$redis_db.&#39;__:expired&#39;), &#39;keyCallback&#39;);
// 回调函数,这里写处理逻辑
function keyCallback($redis, $pattern, $channel, $msg)
{
    echo PHP_EOL;
    echo "Pattern: $pattern\n";
    echo "Channel: $channel\n";
    echo "Payload: $msg\n\n";
    $list = explode(&#39;:&#39;,$msg);

    $order_sn = isset($list[0])?$list[0]:&#39;0&#39;;
    $use_mysql = isset($list[1])?$list[1]:&#39;0&#39;;

    if($use_mysql == 1){
        require_once &#39;db.class.php&#39;;
        $mysql = new \mysql();
        $mysql->connect();
        $where = "ordersn = &#39;".$order_sn."&#39;";
        $mysql->select(&#39;order&#39;,&#39;&#39;,$where);
        $finds=$mysql->fetchAll();
        print_r($finds);
        if(isset($finds[0][&#39;status&#39;]) && $finds[0][&#39;status&#39;]==0){
            $data   = array(&#39;status&#39; => 3);
            $where  = " id = ".$finds[0][&#39;id&#39;];
            $mysql->update(&#39;order&#39;,$data,$where);
        }
    }

}


//或者
/*$redis->psubscribe(array(&#39;__keyevent@&#39;.$redis_db.&#39;__:expired&#39;), function ($redis, $pattern, $channel, $msg){
    echo PHP_EOL;
    echo "Pattern: $pattern\n";
    echo "Channel: $channel\n";
    echo "Payload: $msg\n\n";
    //................
});*/

Note: At the beginning, we declare the path of the php compiler:

#! /usr/bin/env php

This is necessary to execute the php script.

Then, nohup executes psubscribe.php without suspending it. Note the &

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

at the end: the script has indeed started running on process No. 4456.

Check nohup.out cat nohuo.out to see if there is any expired output:

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

Run index.php, after 3 seconds the effect is as above and it is successful

Encounter Problem: Use the command line mode to open the monitoring script. After a while, an error is reported: 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执行成功后直接关闭终端。这样才能保证命令一直在后台运行。

The above is the detailed content of Use PHP+Redis to implement delayed tasks and automatically cancel orders (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete