ThinkPHP 實現隊列

官方文檔: top-think/think-queue

/*1.先在控制器裏添加下面兩個方法*/
namespace app\index\controller;
use think\Controller;
use think\Queue;
use think\Db;
class Index extends Controller
{
    public function queueTest(){
        $data = [
            'order_no' =>rand(100000,999999),
        ];
        $this->add($data['order_no']);
        $data = json_encode($data);
        $res =Queue::push('Job1', $data, $queue = null);
        var_dump($res);
        
    }
    public function add($orderNo){
        $data =[
            'order_no'=>$orderNo,
            'msg'=>$orderNo,
            'create_time'=>date('Y-m-d H:i:s'),
        ];
        Db::name('tp5_test')->insert($data);
    }
}
/*2.在app/job/Job1.php創建文件,並添加如下代碼*/ //Job1 這個在app\job 下新建一個.php 寫一個Job1類 namespace app\job; use think\queue\Job; use think\Db; use think\Controller; class Job1 extends Controller { public function fire(Job $job, $data) { //....這裏執行具體的任務 $data = json_decode($data,true); if($this->jobDone($data)) { $job->delete(); print("<info>Hello Job has been done and deleted"."</info>\n"); }else{ $job->release(3); //$delay爲延遲時間 } if ($job->attempts() > 3) { //通過這個方法可以檢查這個任務已經重試了幾次了 } //如果任務執行成功後 記得刪除任務,不然這個任務會重複執行,直到達到最大重試次數後失敗後,執行failed方法 // $job->delete(); // 也可以重新發布這個任務 // $job->release($delay); //$delay爲延遲時間 } public function failed($data) { // ...任務達到最大重試次數後,失敗了 } public function jobDone($data) { print("<info>Job is Done status!"."</info> \n"); return Db::name('tp5_test')->where('order_no',$data['order_no'])->update(['status'=>2]); } }
/*3. 添加兩張表*/ //數據測試表 DROP TABLE IF EXISTS `tp5_test`; CREATE TABLE `tp5_test` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `order_no` varchar(50) NOT NULL COMMENT '訂單號', `msg` varchar(255) NOT NULL COMMENT '消息內容', `status` tinyint(1) NOT NULL COMMENT '狀態 0未執行,1 執行', `create_time` datetime NOT NULL COMMENT '創建時間', `update_time` datetime NOT NULL COMMENT '更新時間', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='測試表'; //消息隊列表 DROP TABLE IF EXISTS `tp5_jobs`; CREATE TABLE `tp5_jobs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `queue` varchar(255) NOT NULL, `payload` longtext NOT NULL, `attempts` tinyint(3) unsigned NOT NULL, `reserved` tinyint(3) unsigned NOT NULL, `reserved_at` int(10) unsigned DEFAULT NULL, `available_at` int(10) unsigned NOT NULL, `created_at` int(10) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

/*4. 消息的創建與推送*/ //在瀏覽器裏打開 http://demain/index/index/queueTest

/* 5.消息的消費與刪除*/ //windows 在 cmd裏在網站根目錄運行 linux找到當前網站根目錄 當然你php命令必須能執行。 php think queue:listen //監聽
//執行一行
php think queue:work --queue -v //循環執行 php think queue:work --daemon //(不加--daemon爲執行單個任務) //最後自己在數據庫中體會隊列原理。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章