Change queue driver in Laravel 5.1 at runtime?

I am using beanstalkd as my queue driver:

# /.env
QUEUE_DRIVER=beanstalkd

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

      

and work in line

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

      

This works great when I submit the job using the controller, but I need one specific route to use the sync driver instead of the beanstalkd driver when submitting the job. Secondary software seemed like the answer here.

# /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;
}

      

However, the job is still being pushed onto the beanstalkd queue.

In other words, how do I change the queue driver at runtime when submitting a job from the controller?

EDIT: Calling config (['queue.default' => 'sync']) seems to work in the Artisan command and not from the Http controller ...

# /app/Conosle/Commands/MyCommand.php

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

      

+3


source to share


2 answers


See what your middleware is doing - $ next ($ request); is the code that makes the request. As you can see, you are changing the configuration after the request has already been processed. Change

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

      



to

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

      

+1


source


Solved by using this in my controller method:

# /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);
}

      



In my case, \ Queue: push () seems to pay attention to driver changes at runtime, whereas $ this-> dispatch () does not.

+1


source







All Articles