tp6 使用queue


開始就是老生常談的話了,composer安裝queue

composer require topthink/think-queue

安裝完成后在vendor/topthink/think-queue/src目錄下有個config.php 把它復制到根目錄config目錄下,改名為queue.php,有三種模式,同步模式/database(數據庫)/Redis 三種,推薦使用Redis,下面貼一下配置文件代碼

return [
    'default'     => 'database',
    'connections' => [
        'sync'     => [
            'type' => 'sync',
        ],
        'database' => [
            'type'       => 'database',
            'queue'      => 'default',
            'table'      => 'jobs',
        ],
        'redis'    => [
            'type'       => 'redis',
            'queue'      => 'default',
            'host'       => '127.0.0.1',
            'port'       => 6379,
            'password'   => '',
            'select'     => 0,
            'timeout'    => 0,
            'persistent' => false,
        ],
    ],
    'failed'      => [
        'type'  => 'none',
        'table' => 'failed_jobs',
    ],
];

  我用的是數據庫,所以default是database,下面放數據表,字段可能有多余,湊合用吧。

CREATE TABLE `tp_account` (
  `id` bigint(19) NOT NULL,
  `code` varchar(255) DEFAULT NULL,
  `loginID` varchar(255) DEFAULT NULL,
  `remark` varchar(255) DEFAULT NULL,
  `status` tinyint(1) DEFAULT NULL,
  `online` tinyint(1) DEFAULT NULL,
  `cookies` varchar(2500) DEFAULT NULL,
  `openid` varchar(255) DEFAULT NULL,
  `errMsg` varchar(255) DEFAULT NULL,
  `zoneid` varchar(60) DEFAULT NULL,
  `max_amount` int(11) DEFAULT NULL,
  `day_amount` int(11) DEFAULT NULL,
  `time` int(11) DEFAULT NULL,
  `day_time` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

  下面放需要使用消息隊列的場景,我這里的場景是生成支付訂單后沒有回調接口獲取訂單完成情況,只能自己去發起請求去查詢訂單完成與否,所以在生成訂單之后就會投放一個查詢到隊列中。

需要調用消息隊列的頁面。

<?php
namespace app\index\controller;

use think\facade\Queue;
class Index {

public function pay()
    {
         $jobQueueName = 'checkOrder';
         $orderData = ['oid'=>123]; //假設訂單id是123
         $isPushed = Queue::later(3,Job1::class,$orderData,$jobQueueName);
    }
}

  消息隊列頁面

<?php
namespace app\job;

use think\queue\Job;

class Job1{

    public function fire(Job $job, $data){
           if($this->queryOrder($data['oid]){
                  //修改訂單狀態完成
                 $job->delete();
                 return true;
           }else if($job->attempts() >60){ //查詢60次后依然沒有結果,刪除隊列,停止查詢,該訂單判定為未支付。
                 $job->delete();
                 return false;
            }else{
                 $job->release(2); //如果查詢不到60次,並且還未支付成功,就延時兩秒重新投放到隊列中查詢。
                 return true
            }
    }
    public function queryOrder($id){
        //這里寫查詢訂單的邏輯,查詢訂單是否已支付
        return true;
    }
    public function failed($data){

        // ...任務達到最大重試次數后,失敗了
    }
}                

  ok,寫完了,最后在tp6 根目錄下運行php think queue:work --queue checkOrder,就能讓這條消息隊列執行起來了, --queue后面的名稱是一開始傳到消息隊列的隊列名。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM