Home >PHP Framework >Laravel >Examples to explain the simple use of Laravel queues

Examples to explain the simple use of Laravel queues

WBOY
WBOYforward
2022-02-25 18:01:452750browse

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

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,
],

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

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 *******************/

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

{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

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:*

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

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

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)
{
// 给用户发送失败通知,等等...
}
}

[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:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete