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.
[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!

Laravel is suitable for building web applications quickly, while Python is suitable for a wider range of application scenarios. 1.Laravel provides EloquentORM, Blade template engine and Artisan tools to simplify web development. 2. Python is known for its dynamic types, rich standard library and third-party ecosystem, and is suitable for Web development, data science and other fields.

Laravel and Python each have their own advantages: Laravel is suitable for quickly building feature-rich web applications, and Python performs well in the fields of data science and general programming. 1.Laravel provides EloquentORM and Blade template engines, suitable for building modern web applications. 2. Python has a rich standard library and third-party library, and Django and Flask frameworks meet different development needs.

Laravel is worth choosing because it can make the code structure clear and the development process more artistic. 1) Laravel is based on PHP, follows the MVC architecture, and simplifies web development. 2) Its core functions such as EloquentORM, Artisan tools and Blade templates enhance the elegance and robustness of development. 3) Through routing, controllers, models and views, developers can efficiently build applications. 4) Advanced functions such as queue and event monitoring further improve application performance.

Laravel is not only a back-end framework, but also a complete web development solution. It provides powerful back-end functions, such as routing, database operations, user authentication, etc., and supports front-end development, improving the development efficiency of the entire web application.

Laravel is suitable for web development, Python is suitable for data science and rapid prototyping. 1.Laravel is based on PHP and provides elegant syntax and rich functions, such as EloquentORM. 2. Python is known for its simplicity, widely used in Web development and data science, and has a rich library ecosystem.

Laravelcanbeeffectivelyusedinreal-worldapplicationsforbuildingscalablewebsolutions.1)ItsimplifiesCRUDoperationsinRESTfulAPIsusingEloquentORM.2)Laravel'secosystem,includingtoolslikeNova,enhancesdevelopment.3)Itaddressesperformancewithcachingsystems,en

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools