zl程序教程

您现在的位置是:首页 >  大数据

当前栏目

laravel job 队列

队列队列 laravel job
2023-09-14 09:12:11 时间

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。