Table of Contents
When to use queue?
1. Configure queue storage
2. Create a task class
3. Start Queue task
4. Supervisor configuration
5. Handling failed tasks
6. Clear failed tasks
Home PHP Framework Laravel Examples to explain the simple use of Laravel queues

Examples to explain the simple use of Laravel queues

Feb 25, 2022 pm 06:01 PM
laravel

This article brings you laravel related knowledge, which mainly introduces Laravel queues, under what circumstances to use queues, configure queue storage and other related issues. I hope it will be helpful to everyone.

Examples to explain the simple use of Laravel queues

[Related recommendations: laravel learning tutorial

This article will introduce how to use queues in Laravel and understand why they are used. Queue

When to use queue?

Time-consuming, such as uploading a file and then performing some format conversions, etc.

If you need to ensure the delivery rate, such as sending a text message, because you have to call someone else's API, there is always a chance of failure. In order to ensure delivery, retrying is essential.

Record the usage process:

1. Configure queue storage

The queue configuration file is stored in config/queue.php. The default is sync synchronization processing. Here you can choose redis, database etc. The usage method is as follows.

Database

Create a data table storage task and run data migration after executing the artisan command

php artisan queue:table
php artisan migrate
Copy after login

Redis

In order to use the redis queue driver, you need to Configure the Redis database connection in your configuration file config/database.php.

If your Redis queue connection uses Redis cluster, your queue name must contain the key hash tag. This is to ensure that all Redis keys for a given queue are placed in the same hash:

'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'retry_after' => 90,
],
Copy after login

2. Create a task class

The task class for the queue is in the app/Jobs/ directory Next

php artisan make:job SaveBusLine

Modify the file as follows:

namespace App\Jobs;
use App\Http\Repository\BusRepository;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class SaveBusLine implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* 任务最大尝试次数。
*
* @var int
*/
public $tries = 3;
/**
* 任务运行的超时时间。
*
* @var int
*/
public $timeout = 60;
private $datum;
/**
* Create a new job instance.
* @param array|object $datum
*
* @return void
*/
public function __construct($datum)
{
$this->datum = $datum;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
BusRepository::getInstent()->updateBusLine($this->datum);
}
}
Copy after login

Call the queue method in the controller or warehouse:

use App\Jobs\SaveBusLine;
use Carbon\Carbon;
/***************** 队列操作 start *******************/
SaveBusLine::dispatch($arrayData)->delay(Carbon::now()->addMinute(1));
/***************** 队列操作 end *******************/
Copy after login

3. Start Queue task

php artisan queue:work

4. Supervisor configuration

Installing Supervisor

Supervisor is a Linux operating system Process monitoring software that automatically restarts queue:listen or queue:work commands after they fail. To install Supervisor on Ubuntu, you can use the following command:

sudo apt-get install supervisor
Copy after login

{tip} If configuring Supervisor manually sounds a bit overwhelming, you can consider using Laravel Forge, which can automatically install and configure Supervisor for your Laravel project.

Configuring Supervisor

Supervisor configuration files are generally placed in the /etc/supervisor/conf.d directory. In this directory you can create any number of configuration files to tell the Supervisor how to monitor your processes. For example, we create a laravel-worker.conf to start and monitor a queue:work process:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php ~/laravel/artisan queue:work redis --sleep=3 --tries=3
autostart=true
autorestart=true
user=lisgroup
numprocs=8
redirect_stderr=true
stdout_logfile=/home/lisgroup/logs/worker.log
Copy after login

The numprocs command in this example will ask Supervisor to run and monitor 8 queue:work processes, and when they fail to run and then restart. Of course, you must change the queue:work redis command command to display the queue driver of your choice. You also need to modify the execution user user=XXX

Start Supervisor

After this configuration file is created, you need to update the Supervisor configuration and use the following command to start the Supervisor Process:

sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start laravel-worker:*
Copy after login

For more information about the setting and use of Supervisor, please refer to the Supervisor official documentation.

5. Handling failed tasks

Sometimes tasks in your queue will fail. Don't worry, things won't always be smooth sailing. Laravel has a built-in convenient way to specify the maximum number of times a task will be retried. When a task exceeds this number of retries, it will be inserted into the failed_jobs data table. To create a migration file for the failed_jobs table, you can use the queue:failed-table command, and then use the migrate Artisan command to generate the failed_jobs table:

php artisan queue:failed-table
php artisan migrate
Copy after login

Then run the queue processor, and when calling the queue worker, you should pass the command The --tries parameter specifies the maximum number of retries for the task. If not specified, the task will be retried permanently:

php artisan queue:work redis --tries=3
Copy after login

6. Clear failed tasks

You can directly define the failed method in the task class, which can run the task cleanup when the task fails. logic. This place is perfect for sending a warning to the user or resetting the operation of the task execution. Exception information that causes the task to fail will be passed to the failed method:

namespace App\Jobs;
use Exception;
use App\Podcast;
use App\AudioProcessor;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class ProcessPodcast implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
protected $podcast;
/**
* 创建一个新的任务实例。
*
* @param Podcast $podcast
* @return void
*/
public function __construct(Podcast $podcast)
{
$this->podcast = $podcast;
}
/**
* 执行任务。
*
* @param AudioProcessor $processor
* @return void
*/
public function handle(AudioProcessor $processor)
{
// 处理上传播客...
}
/**
* 要处理的失败任务。
*
* @param Exception $exception
* @return void
*/
public function failed(Exception $exception)
{
// 给用户发送失败通知,等等...
}
}
Copy after login

[Related recommendations: laravel video tutorial]

The above is the detailed content of Examples to explain the simple use of Laravel queues. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

See all articles