php异步处理任务 使用redis消息队列

安装redis 和 php-redis扩展,参考网友博文

linux环境   https://blog.csdn.net/cailongbiaoyuli/article/details/83445906

windows环境  https://blog.csdn.net/q810391679/article/details/80812578

 

通过生产消费模式实现异步处理 ,把待运行任务添加到消息队列, 定时从队列取出消息处理任务;

定时处理任务的方法,

linux环境下,添加到corntab,每1分钟运行一次

# crontab -e

*/1 * * * * /usr/local/bin/php /home/www/app.php?do=worker

windows环境下,添加到计划任务,计划任务运行bat文件,bat中调用php执行脚本

tmp.bat

D:\php56\php.exe -q E:\www\201906\app.php?do=worker

 

 

<?php
// 发布消息
// app.php?do=rpush&act=sendsms&mob=15530000000&msg=tmp_order_new
// 定时任务 消费消息
// app.php?do=worker
$conf = ['redis_host'=>'127.0.0.1', 'redis_port'=>6379, 'redis_auth'=>'6min']
$app = new appStd($conf);
$app->run();

class appStd
{
    private static $redis;
    
    public function __construct($conf){
        if(! (static::$redis instanceof Redis)) {
            self::$redis = new Redis();
            self::$redis->connect($conf['redis_host'], $conf['redis_port']);
            if(isset($conf['reids_authpass'])){
                self::$redis->auth($conf['redis_auth']);
            }
        }
    }

    public function worker($param){
        //ignore_user_abort(true);
        set_time_limit(30);
        while (true) {
            try{
                $cmd = self::$redis->get('cmd');
                if('stop' == $cmd) break;
                //取出一条消息
                $msg = self::$redis->lPop('msglist');
                if(!$msg) break;
                $wk = unserialize($msg);
                switch($wk['act']){
                    case 'sendsms':
                        $do = SMS::send($wk['data']);
                        break;
                    case 'report':
                        $do = YUN::report($wk['data']);
                        break;
                }
                //失败任务放回队列
                if(!$do){
                    self::$redis->rPush('msglist', $msg);
                }
            }catch(Exception $e){
                die($e->getMessage());
            }
        }
        die('success');
    }

    public function rpush($param){
        $msg = ['act'=>$param['act'], 'data'=>[]];
        self::$redis->rPush('msglist', serialize($msg));
        die('success');
    }
    
    public function run(){
        $param  = &$_REQUEST;
        $action = isset($param['do']) ? $param['do'] : '';
        if( !method_exists($this, $action)){
            $this->fail('disabled action');
        }
        $this->$action($param);
    }
}
posted @ 2019-06-26 14:51  1553  阅读(2495)  评论(0编辑  收藏  举报