【问题标题】:How to dispatch an async job in Laravel 5.8 with Redis?如何使用 Redis 在 Laravel 5.8 中调度异步作业?
【发布时间】:2020-07-28 23:28:53
【问题描述】:

我需要在 Laravel 5.8 中异步运行一个非常耗时的任务。这是.env 文件

...
QUEUE_CONNECTION=sync
QUEUE_DRIVER=redis
...

队列驱动程序必须是Redis,因为网站使用Laravel-Echoredissocket.io 来广播消息,我无法将队列驱动程序更改为database

这是我创建的工作

<?php

namespace App\Jobs;

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

class BroadcastRepeatJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        sleep(30);
    }
}

这是HomeController

public function index()
{
    BroadcastRepeatJob::dispatch()->onQueue("default");
    dd(1);
    ...
}

我还运行以下工匠命令

php artisan queue:work
php artisan queue:listen

当我访问 /indexHomeController 时,我希望不会在 30 秒后立即看到 dd(1),因为 sleep(30) 必须在队列中运行,但这不会发生,我必须等待 30 秒看dd(1)。如何在后台异步运行作业?

提前致谢。

【问题讨论】:

    标签: laravel redis delayed-job


    【解决方案1】:

    尝试将您的 QUEUE_CONNECTION 切换为 redis 而不是 sync

     /*
        |--------------------------------------------------------------------------
        | Queue Connections
        |--------------------------------------------------------------------------
        |
        | Here you may configure the connection information for each server that
        | is used by your application. A default configuration has been added
        | for each back-end shipped with Laravel. You are free to add more.
        |
        | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
        |
        */
    
        'connections' => [
    
            'sync' => [
                'driver' => 'sync',
            ],
    
            'database' => [
                'driver'        => 'database',
                'table'         => 'jobs',
                'queue'         => 'default',
                'retry_after'   => 90,
            ],
    
            'redis' => [
                'driver'        => 'redis',
                'connection'    => 'default',
                'queue'         => env('REDIS_QUEUE', 'default'),
                'retry_after'   => 90,
                'block_for'     => null,
            ],
    
        ],
    

    【讨论】:

    • 感谢您的回复。从.env 我将连接更改为redis。我更改了工作的handle 功能并写了Log::info('From Broadcast job');。运行代码后,没有日志报告,我只看到dd(1)。为了确保调用了句柄函数,我在那里添加了一个语法错误,laravel 报告了该错误,因此我确定它被调用但它没有将日志添加到日志文件中。
    • @MamaD 如果您不使用同步,您还需要启动队列工作人员来处理队列。请参阅documentation。您还可以查看Laravel Horizon,这是一个用于管理队列工作人员的出色软件包。
    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2014-04-29
    • 2015-12-01
    相关资源
    最近更新 更多