【问题标题】:Change the queue driver in Laravel 5.1 at runtime?在运行时更改 Laravel 5.1 中的队列驱动程序?
【发布时间】:2015-08-28 21:44:03
【问题描述】:

我使用 beanstalkd 作为我的队列驱动程序:

# /.env
QUEUE_DRIVER=beanstalkd

# /config/queue.php
'default' => env('QUEUE_DRIVER', 'sync'),

和一个可排队的工作

# /app/Jobs/MyJob.php
class MyJob extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    ....
    ....
}

当我通过控制器调度作业时,这很有效,但我希望在调度时使用 sync 驱动程序而不是 beanstalkd 驱动程序的特定路线工作。中间件似乎是这里的答案

# /app/Http/Controllers/MyController.php
public function create(Request $request)
{
    $this->dispatch(new \App\Jobs\MyJob());
}

# /app/Http/routes.php
Route::post('/create', ['middleware' => 'no_queue', 'uses' => 'MyController@create']);

# /app/Http/Middleware/NoQueue.php
public function handle($request, Closure $next)
{
    $response = $next($request);
    config(['queue.default'=>'sync']);
    return $response;
}

但是,作业仍在被推送到 beanstalkd 队列。

换句话说,当从控制器调度作业时,如何在运行时更改队列驱动程序?

编辑: 调用 config(['queue.default'=>'sync']) 确实 似乎可以在 Artisan 命令中工作,而不是来自 Http 控制器...... p>

# /app/Conosle/Commands/MyCommand.php

class ScrapeDrawing extends Command
{
    use DispatchesJobs;
    ...
    ...
    public function handle()
    {
        config(['queue.default'=>'sync'])
        $this->dispatch(new \App\Jobs\MyJob());
    }
}

【问题讨论】:

  • Queue::driver('sync')->push(new \App\Jobs\MyJob());怎么样
  • Call to undefined method Illuminate\Queue\Queue::driver()

标签: php laravel laravel-5 laravel-5.1


【解决方案1】:

在我的控制器方法中使用这个解决了:

# /app/Http/Controllers/MyController.php
public function create(Request $request, QueueManager $queueManager)

    $defaultDriver = $queueManager->getDefaultDriver();

    $queueManager->setDefaultDriver('sync');

    \Queue::push(new \App\Jobs\MyJob());

    $queueManager->setDefaultDriver($defaultDriver);
}

在我的例子中,\Queue:push() 似乎在运行时关注驱动程序的变化,而 $this->dispatch() 没有。

【讨论】:

    【解决方案2】:

    看看你的中间件做了什么 - $next($request); 是执行请求的代码。如您所见,您正在处理请求后更改配置。改变

    public function handle($request, Closure $next)
    {
      $response = $next($request);
      config(['queue.default'=>'sync']);
      return $response;
    }
    

    public function handle($request, Closure $next)
    {
      config(['queue.default'=>'sync']);
      $response = $next($request);
      return $response;
    }
    

    【讨论】:

    • 很好,但仍然没有骰子。作业仍在被推送到 beanstalkd。
    • 你确定吗?我在我们的一个中间件中做到了这一点,它可以工作——而不是数据库队列,我得到了 SyncQueue 对象。您如何检查使用了哪个队列?
    • 我看到工作正在 ptrofimov/beanstalk_console 中处理。您是否在 .env 中设置队列驱动程序?
    猜你喜欢
    • 1970-01-01
    • 2016-06-10
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多