Laravel 5.5 Queue

本文详细介绍如何使用队列进行任务分发、延时分发、任务链处理、设置最大失败次数及超时时间,同时讲解了如何运行队列进程、处理失败任务及监听任务事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Queue(队列)

// 分发任务
    dispatch(new Job);  // 以下的任务将被委派到默认队列...
    dispatch((new Job)->onQueue('emails'));  // 以下任务将被委派到 "emails" 队列...
    ProcessPodcast::dispatch($podcast)->onConnection('sqs');  // 分发到指定的连接
    ProcessPodcast::dispatch($podcast);
    
    (延时分发)
        ProcessPodcast::dispatch($podcast)
                        ->delay(now()->addMinutes(10));
    
    (任务链)
        ProcessPodcast::withChain([
            new OptimizePodcast,
            new ReleasePodcast
        ])->dispatch();
    
    (指定最大失败次数/超时时间)
        * 最大失败次数
            php artisan queue:work --tries=3
            public $tries = 5;
        
        * 基于时间的尝试次数
            public function retryUntil()
            {
                return now()->addSeconds(5);
            }
        
        * 超时
            php artisan queue:work --timeout=30 // 单位为 秒
            public $timeout = 120;

// 运行队列进程
    (处理单个任务)
        php artisan queue:work --once
    
    (指定连接和队列)
        php artisan queue:work redis
        php artisan queue:work redis --queue=emails
    
    (队列优先级)
        dispatch((new Job)->onQueue('high'));
        php artisan queue:work --queue=high,low
    
    (队列进程 & 部署)
        php artisan queue:restart

// 处理失败的任务
    php artisan queue:failed-table  // 记录任务失败表

    public function failed(Exception $exception)
    {
        // 发送失败通知, etc...
    }

    * 重试失败的任务
        php artisan queue:failed  // 查看已插入到 failed_jobs 数据表中的所有失败任务
        php artisan queue:retry 5  // 重试一个 ID 为 5 的失败任务
        php artisan queue:retry all  // 重试所有失败任务
        php artisan queue:forget 5  // 删除一个失败任务
        php artisan queue:flush  // 删除所有失败任务

// 任务事件
    Queue 门面提供的 before 和 after 方法可以在任务被处理之前或之后指定要执行的回调。通常,你可以在服务提供者中使用这些方法。比如,我们可能在AppServiceProvider 这样用
    
    public function boot()
    {
        Queue::before(function (JobProcessing $event) {
            // $event->connectionName
            // $event->job
            // $event->job->payload()
        });

        Queue::after(function (JobProcessed $event) {
            // $event->connectionName
            // $event->job
            // $event->job->payload()
        });
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值