Lumen队列使用

  1. 队列使用
    1. 队列配置 config\queue.php
    2. 队列继承基础类app\Jobs\Job.php
    3. 队列生产类app\Jobs\UpdateSucaiPrJob.php
    4. 消费队列

队列使用

队列配置 config\queue.php

<?php
return [
    // 配置默认使用connections配置的设备信息
    'default' => env('QUEUE_DRIVER', 'redis'),

    // 设备链接配置
    'connections' => [
        'database' => [
            'driver' => 'database',
            'table' => 'jobs',
            'queue' => 'default',
            'expire' => 60,
        ],
        'redis' => [
            'driver' => 'redis',        // 设备
            'connection' => 'queue',    // 链接
            'queue' => 'default',       // 默认队列
            'expire' => 60,             // 过期时间
        ],
    ],

    // 错误信息存储配置
    'failed' => [
        'database' => 'mysql', 'table' => 'jobs_failed',
    ],
];

队列继承基础类app\Jobs\Job.php

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

abstract class Job implements ShouldQueue
{
    /*
    |--------------------------------------------------------------------------
    | Queueable Jobs
    |--------------------------------------------------------------------------
    |
    | This job base class provides a central location to place any logic that
    | is shared across all of your jobs. The trait included with the class
    | provides access to the "queueOn" and "delay" queue helper methods.
    |
    */

    use InteractsWithQueue, Queueable, SerializesModels;
}

队列生产类app\Jobs\UpdateSucaiPrJob.php

<?php

namespace App\Jobs;

use App\Models\Sucai;
use Exception;

class UpdateSucaiPrJob extends Job
{
    protected $data = [];

    // 最大失败次数
    public $tries = 5;

    // 超时设置
    public $timeout = 120;

    /**
     * Create a new job instance.
     *
     * @return array
     */
    public function __construct(array $data)
    {
        // 定义onQueue 执行:
        $this->onQueue('UpdateSucaiPrQueue');
        // 设置延迟
        $this->delay(0);
        $this->data = $data;
    }

    /**
     * Execute the job.
     * 执行命令:php artisan queue:work --daemon --queue=UpdateSucaiPrQueue
     *
     * @return void
     */
    public function handle()
    {
        // 处理队列程序,更新素材展示次数
        Sucai::whereIn('id', $this->data)->increment('shows');
    }

    /**
     * 任务失败的处理过程
     *
     * @param  Exception  $exception
     * @return void
     */
    public function failed(Exception $exception)
    {
        // 给用户发送任务失败的通知,等等……
    }
}

消费队列

# 命令行
php artisan queue:work --queue=UpdateSucaiPrQueue

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 [email protected]

×

喜欢就点赞,疼爱就打赏