配置.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
- 生成檔案如圖:
- 編寫任務程式碼:
<?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
然後再重新消費佇列…
結果
日誌:
本作品採用《CC 協議》,轉載必須註明作者和本文連結