Laravel消息队列怎么使用

使用database驱动做队列

下面是简单使用教程

1. 修改.env文件配置

QUEUE_CONNECTION=sync改成QUEUE_CONNECTION=database
默认的sync是同步队列

2. 添加消息队列的mysql表

php artisan queue:table
php artisan migrate

3. 创建任务类

php artisan make:job WangZhaoBo

然后生成该路径文件appJobsWangZhaoBo.php
打开改文件,复制下面的代码覆盖掉生成代码

<?php

namespace AppJobs;

use IlluminateBusQueueable;
use IlluminateQueueSerializesModels;
use IlluminateQueueInteractsWithQueue;
use IlluminateContractsQueueShouldQueue;
use IlluminateFoundationBusDispatchable;

class WangZhaoBo implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $name;

//        //这里可以声明最大尝试次数
//    public $trie = 3;

//    //优先执行service队列
//    php artisan queue:work --queue=service,default --tries=3
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($name)
    {
        $this->name = $name;
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        sleep(2);
        $res = file_put_contents('abcdef.log',$this->name.date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
//        if ($res===false) {
//            // 延迟 10s 后推送,默认是 0,表示立即推送
//            $this->release(10);
             //你可以可以根据已执行次数依次递增延迟时间:
//           $this->release(10 * $this->attempts());
//        }
    }

    //failed_jobs
    // 任务执行失败后发送邮件通知给相关人员
    public function failed(Exception $exception){
        Mail::to($this->service->developer->email)->send('...');
    }
}

4. 运行消息队列

php artisan queue:work

5. 调用消息队列

这两个方法返回值不同,可方法一返回的是mysql表的id.方法二是返回队列的对象.可以自己打印一下看看
delay(10)是延迟10秒执行

//方法一
$this->dispatch((new WangZhaoBo('王召波'))->delay(10));
//方法二
WangZhaoBo::dispatch('王召波')->delay(10);

把上面的方法放到控制器里面,然后访问一下.
你会看到命令窗口显示

[2021-01-28 13:59:42][333] Processing: AppJobsWangZhaoBo
[2021-01-28 13:59:42][333] Processed:  AppJobsWangZhaoBo

然后你在项目根目录会生成一个abcdef.log文件

注意事项

  1. 因为队列是常驻进程,所以队列类WangZhaoBo内容修改的时候,需要重新启动队列才能生效
    在window使用cmd窗口运行队列之后,再使用restart之后,之前队列会自动断掉.
>php artisan queue:restart
>php artisan queue:work
  1. 如果你的队列类报错了,队列一直执行,表中的attempts字段到255之后.
    队列就不执行了,这个时候把255改成0再去执行队列

参考:
https://learnku.com/docs/laravel/5.7/queues/2286#connections-vs-queues
https://blog.csdn.net/qq_39173140/article/details/98491547
https://blog.csdn.net/chen529834149/article/details/76918406/
https://wiki.jikexueyuan.com/project/laravel-5.1/queue.html

原文地址:https://www.cnblogs.com/wangzhaobo/p/WangZhaoBo.html