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