如何使用 Redis 在 Laravel 5.8 中分派异步作业?

How to dispatch an async job in Laravel 5.8 with Redis?

我需要在 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);
    ...
}

我还运行以下artisan命令

php artisan queue:work
php artisan queue:listen

当我访问 HomeController/index 时,我希望立即看到 dd(1),而不是在 30 秒之后,因为 sleep(30) 必须是 运行 在队列中,但这并没有发生,我必须等待 30 秒才能看到 dd(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,
        ],

    ],