I'm using beanstalkd as my queue driver:
# /.env
QUEUE_DRIVER=beanstalkd
# /config/queue.php
'default' => env('QUEUE_DRIVER', 'sync'),
and a queue-able job
# /app/Jobs/MyJob.php
class MyJob extends Job implements SelfHandling, ShouldQueue
{
use InteractsWithQueue, SerializesModels;
....
....
}
This works great when I dispatch the job via a controller, but I'd like one particular route to use the sync driver instead of the beanstalkd driver when dispatching the job. Middleware 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 to the beanstalkd queue.
In other words, how does one change the queue driver at runtime when dispatching a job from a controller?
EDIT: Calling config(['queue.default'=>'sync']) does seem to work in an Artisan command, just not from an 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());
}
}
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 the driver change at runtime whereas $this->dispatch() doesn't.
Have a look at what your middleware does - $next($request); is the code that executes the request. As you can see, you are changing the config after request is already 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.