如何在带有redis的laravel5.8中调度异步作业?

3pvhb19x  于 2021-06-10  发布在  Redis
关注(0)|答案(1)|浏览(425)

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

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

队列驱动程序必须是redis,因为网站使用 Laravel-Echoredis 以及 socket.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

当我拜访 /indexHomeController 我希望看到 dd(1) 立即而不是之后 30 因为 sleep(30) 必须在队列中运行,但这不会发生,我必须等待30秒才能看到 dd(1) . 如何在后台异步运行作业?
提前谢谢。

uidvcgyl

uidvcgyl1#

尝试切换你的 QUEUE_CONNECTIONredis 而不是 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,
    ],

],

相关问题