thinkphp6.0 使用 topthink/queue 3.0 示例


安装 composer require topthink/think-queue ^3.0

PS:如果有问题的话可以查看一篇文章关于BUG修复。

添加配置文件

<?php
return [
    'default' => 'redis',
    'connector' => 'redis',
    'connectors' => [
        'redis' => [
            'driver' => 'redis',
            'queue' => 'default',
            'host' => '127.0.0.1',
            'port' => 6379,
            'password' => '',
            'select' => 0,
            'timeout' => 3600,
            'persistent' => false,
        ],
    ],
    'failed'      => [
        'type'  => 'none',
        'table' => 'failed_jobs',
    ],
];

示例入口文件:

<?php
namespace app\controller;

use app\BaseController;
use think\facade\Queue;
class Index extends BaseController
{
    public function index()
    {
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V' . \think\facade\App::version() . '<br/><span style="font-size:30px;">14载初心不改 - 你值得信赖的PHP框架</span></p><span style="font-size:25px;">[ V6.0 版本由 <a href="https://www.yisu.com/" target="yisu">亿速云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="ee9b1aa918103c4fc"></think>';
    }

    public function hello($name = 'ThinkPHP6')
    {
        return 'hello,' . $name;
    }

    public function test(){
      
        // 1.当前任务将由哪个类来负责处理。 
        //   当轮到该任务时,系统将生成一个该类的实例,并调用其 fire 方法
        $jobHandlerClassName  = 'app\job\Hello@fire'
        
        // 2.当前任务归属的队列名称,如果为新队列,会自动创建
        $jobQueueName     = "helloJobQueue"
        
        
        // 3.当前任务所需的业务数据 . 不能为 resource 类型,其他类型最终将转化为json形式的字符串
        //   ( jobData 为对象时,存储其public属性的键值对 )
        $jobData          = '1111111' ;
        // 4.将该任务推送到消息队列,等待对应的消费者去执行
        $isPushed = Queue::push$jobHandlerClassName , $jobData , $jobQueueName );
        // $time2wait =  60; 
        // $isPushed = Queue::later($time2wait, $jobHandlerClassName , $jobData , $jobQueueName );

        // database 驱动时,返回值为 1|false  ;   redis 驱动时,返回值为 随机字符串|false
        if$isPushed !== false ){  
            echo date('Y-m-d H:i:s'. " a new Hello Job is Pushed to the MQ"."<br>";
        }else{
            echo 'Oops, something went wrong.';
        }
    }
}

job文件:

<?php
namespace app\job;

use think\queue\Job;
use think\facade\Log;
class Hello{
    
    public function fire(Job $job,$data)
    {
        file_put_contents('aaaaaaa.txt''aaaaaaaaaaaaa', FILE_APPEND );
        // 有些消息在到达消费者时,可能已经不再需要执行了
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if(!$isJobStillNeedToBeDone){
            $job->delete();
            Log::log('error',"dismiss job has been down and deleted");
            return;
        }
        
        $isJobDone = $this->doHelloJob($data);
        if ($isJobDone) {
            // 如果任务执行成功, 记得删除任务
            $job->delete();
            Log::log('info'"dismiss job has been down and deleted");
        }else{
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                Log::log('alert'"dismiss job has been retried more that 3 times");
                
                $job->delete();
                
                // 也可以重新发布这个任务
                //print("<info>Hello Job will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间,表示该任务延迟2秒后再执行
            }
        }
    }
    
    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data){
        return true;
    }

    /**
     * 根据消息中的数据进行实际的业务处理...
     */
    private function doHelloJob($data
    {
        print("<info>Hello Job Started. job Data is: ".var_export($data,true)."</info> \n");
        print("<info>Hello Job is Fired at " . date('Y-m-d H:i:s'."</info> \n");
        print("<info>Hello Job is Done!"."</info> \n");
        
        return true;
    }
    
    public function failed($data){
    
        // ...任务达到最大重试次数后,失败了
    }

}

?>

添加完毕,在 terminal 运行 php think queue:listen --queue helloJobQueue

访问 ***/index/test 加入队列

你会在 terminal 面板上看到输出内容

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM