laravel8.x --- 訊息佇列 [database] 驅動

MTyu發表於2022-08-12

配置.env

QUEUE_CONNECTION=database

生成資料遷移表

php artisan queue:table   任務佇列表
php artisan queue:failed-table  執行任務失敗後,儲存的表

php artisan migrate  執行遷移
  • jobs表結構
CREATE TABLE `jobs` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `queue` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `payload` longtext COLLATE utf8_unicode_ci NOT NULL,
  `attempts` 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
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  • failed_jobs表結構
CREATE TABLE `failed_jobs` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `uuid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `connection` text COLLATE utf8_unicode_ci NOT NULL,
  `queue` text COLLATE utf8_unicode_ci NOT NULL,
  `payload` longtext COLLATE utf8_unicode_ci NOT NULL,
  `exception` longtext COLLATE utf8_unicode_ci NOT NULL,
  `failed_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

建立測試的佇列任務

php artisan make:job NoticeJob
  • 生成檔案如圖:

laravel8.x  ---  訊息佇列  [database]  驅動

  • 編寫任務程式碼:
<?php

namespace App\Jobs;

use App\Models\Notice;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class NoticeJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $notice;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($notice)
    {
        //
        $this->notice = $notice;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        sleep(10);
        Notice::where('id', $this->notice)->update(['title' => 'demo23']);
        Log::info("修改【notice】:id=>" . $this->notice . "成功");
    }
}

控制器程式碼

    public function demo ()
    {
        NoticeJob::dispatch(2);
        //....
    }

建立路由訪問控制器對應方法

jobs表會新增一條相應資料……

消費佇列任務

php artisan queue:work
  • 成功則對應jobs表中資料會消失
  • 失敗則failed_jobs表中會新增一條對應資料,日誌也會記錄錯誤

注意:每次修改任務程式碼(即handel())需要執行更新指令

php artisan queue:restart

然後再重新消費佇列…

結果

laravel8.x  ---  訊息佇列  [database]  驅動

日誌:

laravel8.x  ---  訊息佇列  [database]  驅動

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章