1.數據庫建表
php artisan queue:table<span> </span>//隊列任務表 php artisan queue:failed-table<span> </span>//任務執行失敗表 php artisan migrate
2.創建job類
<?php
namespace App\Jobs;
use App\Services\TestService;
use Illuminate\Support\Facades\Log;
class CommentInfoJob extends Job
{
public $commentService;
public $user_id;
public $comment_id;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($user_id,$comment_id)
{
$this->user_id = $user_id;
$this->comment_id = $comment_id;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
(new TestService())->testsssss($this->user_id,$this->comment_id);
}
}
3.在job類中,實現邏輯
job主要包括三個函數
- 構造函數 可選,用來傳參
- handle() 必選,實現隊列任務邏輯
- failed() 可選,當任務失敗時執行
4.分發隊列任務
dispatch(new CommentInfoJob($params['user_id'], $params['comment_id']));
5.開啟隊列進程,執行隊列任務
php artisan queue:work
這種方式不能關閉teminal,比較不方便。所以一般使用Supervisor。
以上就可以完成一個簡單的隊列任務。
在laravel中有一個很關鍵的點:配置為database驅動。
在/config/queue.php中,需要將connections設置為database。而這一配置是從.env文件中獲取的
將queue_driver配置為database。
