Laravel 5.5 Queue

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()
        });
    }

猜你喜欢

转载自blog.csdn.net/qq_37910492/article/details/84546417