Understanding the need of laravel queues and setup
Saibal Roy • December 3, 2021
laravel-queuesCaveats for long running http requests
- Taking long time for sending responses over http requests has issues like UI blocking, system slowdown and bad user experiences.
- Http requests that takes more than few seconds should be executed asyncronously.
Queues in Laravel
For this reason to process http requests asynchronously we use jobs and queues.
Create a job
php artisan make:job SendWelcomeEmail
Simulate a long running task in the job handle method of app/Jobs/SendWelcomeEmail.php
public function handle()
{
sleep(3); // To simulate a log running task
\info('This job is executed'); // This will be log in the storage/logs/laravel.log file
}
Configure queue
config/queue.php In the .env : QUEUE_CONNECTION=database (Choose any driver offered in queue.php) php artisan queue:table php artisan migrate
Trigger the job in routes/web.php
Route::get('/', function () {
\App\Jobs\SendWelcomeEmail::dispatch();
});
Running laravel queue worker
php artisan queue:work
Things to remember:
- Queue worker is php process that checks the queues to be processed and run them sequentially by default.
- If you need to process more jobs at the same time then you have to run multiple queue workers. On production these depends on the capability of the infrastructure to handle the number of processes parallely.
Happy learning folks!