用PHP+Redis实现延迟任务 实现自动取消订单(详细教程)-php教程

资源魔 37 0
简略按时义务处理计划:应用redis的keyspace notifications(键生效后告诉事情) 需求留意此性能是正在redis 2.8版本当前推出的,因而你效劳器上的reids起码要是2.8版本以上;

(A)营业场景:

一、当一个营业触发当前需求启动一个按时义务,正在指按时间内再去执行一个义务(如主动勾销定单,主动实现定单等性能)

二、redis的keyspace notifications 会正在key生效后发送一个事情,监听此事情的的客户端就能够收到告诉

(B)效劳预备:

一、修正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

<?phpclass 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

<?php

require_once 'Redis2.class.php';

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

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

$list = [$order_sn,$use_mysql];
$key = implode(':',$list);

$redis->setex($key,3,'redis提早义务');      //3秒后回调



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

echo $order_sn;



/*
 *   测试其余key会没有会有回调,后果:有回调
 *   $k = 'test';
 *   $redis2->set($k,'100');
 *   $redis2->expire($k,10);
 *
*/

psubscribe.php

<?php
ini_set('default_socket_timeout', -1);  //没有超时
require_once 'Redis2.class.php';
$redis_db = '15';
$redis = new \Redis2('127.0.0.1','6379','',$redis_db);
// 处理Redis客户端定阅时分超时状况
$redis->setOption();
//当key过时的时分就看到告诉,定阅的key __keyevent@<db>__:expired 这个格局是固定的,db代表的是数据库的编号,因为定阅开启之后这个库的一切key过时工夫城市被推送过去,以是最佳独自应用一个数据库来进行隔离
$redis->psubscribe(array('__keyevent@'.$redis_db.'__:expired'), 'keyCallback');
// 回调函数,这里写解决逻辑
function keyCallback($redis, $pattern, $channel, $msg)
{
    echo PHP_EOL;
    echo "Pattern: $pattern\n";
    echo "Channel: $channel\n";
    echo "Payload: $msg\n\n";
    $list = explode(':',$msg);

    $order_sn = isset($list[0])?$list[0]:'0';
    $use_mysql = isset($list[1])?$list[1]:'0';

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

}


//或许
/*$redis->psubscribe(array('__keyevent@'.$redis_db.'__:expired'), 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 = '127.0.0.1', $port = '6379',$password = '',$db = '15')
    {
        $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零碎测试办法:先正在cmd饬令界面运转psubscribe.php,而后网页关上index.php。

使监听后盾始终运转(定阅)

有个成绩 做到这一步,行使 phpredis 扩大,胜利正在代码里完成对过时 Key 的监听,并正在 psCallback()里进行回调解决。扫尾提出的两个需要曾经完成。可是这里有个成绩:redis 正在执行完定阅操作后,终端进入梗阻状态,需求不断挂正在那。且此定阅剧本需求工钱正在饬令行执行,没有合乎实际需要。

实际上,咱们对过时监听回调的需要,是心愿它像守护过程同样,正在后盾运转,当有过时事情的音讯时,触发还调函数。使监听后盾始终运转 心愿像守护过程同样正在后盾同样,

我是这样完成的。

Linux中有一个nohup饬令。性能就是没有挂断地运转饬令。同时nohup把剧本顺序的一切输入,都放到以后目次的nohup.out文件中,假如文件不成写,则放到<用户主目次>/nohup.out 文件中。那末有了这个饬令当前,不论咱们终端窗口能否封闭,都可以让咱们的php剧本不断运转。

编写psubscribe.php文件:

<?php
#! /usr/bin/env php
ini_set('default_socket_timeout', -1);  //没有超时
require_once 'Redis2.class.php';
$redis_db = '15';
$redis = new \Redis2('127.0.0.1','6379','',$redis_db);
// 处理Redis客户端定阅时分超时状况
$redis->setOption();
//当key过时的时分就看到告诉,定阅的key __keyevent@<db>__:expired 这个格局是固定的,db代表的是数据库的编号,因为定阅开启之后这个库的一切key过时工夫城市被推送过去,以是最佳独自应用一个数据库来进行隔离
$redis->psubscribe(array('__keyevent@'.$redis_db.'__:expired'), 'keyCallback');
// 回调函数,这里写解决逻辑
function keyCallback($redis, $pattern, $channel, $msg)
{
    echo PHP_EOL;
    echo "Pattern: $pattern\n";
    echo "Channel: $channel\n";
    echo "Payload: $msg\n\n";
    $list = explode(':',$msg);

    $order_sn = isset($list[0])?$list[0]:'0';
    $use_mysql = isset($list[1])?$list[1]:'0';

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

}


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

留意:咱们正在扫尾,声明 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执行胜利后间接封闭终端。这样能力保障饬令不断正在后盾运转。

以上就是用PHP+Redis完成提早义务 完成主动勾销定单(具体教程)的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学 Redis 延迟任务

抱歉,评论功能暂时关闭!