search
HomePHP FrameworkLaravelExamples to explain the simple use of Laravel queues

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. If there is any infringement, please contact admin@php.cn delete
What is the latest Laravel version?What is the latest Laravel version?May 09, 2025 am 12:09 AM

As of October 2023, Laravel's latest version is 10.x. 1.Laravel10.x supports PHP8.1, improving development efficiency. 2.Jetstream improves support for Livewire and Inertia.js, simplifies front-end development. 3.EloquentORM adds full-text search function to improve data processing performance. 4. Pay attention to dependency package compatibility when using it and apply cache optimization performance.

Laravel Migrations: A Beginner's Guide to Database ManagementLaravel Migrations: A Beginner's Guide to Database ManagementMay 09, 2025 am 12:07 AM

LaravelMigrationsstreamlinedatabasemanagementbyprovidingversioncontrolforyourdatabaseschema.1)Theyallowyoutodefineandsharethestructureofyourdatabase,makingiteasytomanagechangesovertime.2)Migrationscanbecreatedandrunusingsimplecommands,ensuringthateve

Laravel migration: Best coding guideLaravel migration: Best coding guideMay 09, 2025 am 12:03 AM

Laravel's migration system is a powerful tool for developers to design and manage databases. 1) Ensure that the migration file is named clearly and use verbs to describe the operation. 2) Consider data integrity and performance, such as adding unique constraints to fields. 3) Use transaction processing to ensure database consistency. 4) Create an index at the end of the migration to optimize performance. 5) Maintain the atomicity of migration, and each file contains only one logical operation. Through these practices, efficient and maintainable migration code can be written.

Latest Laravel Version: Stay Up-to-Date with the Newest FeaturesLatest Laravel Version: Stay Up-to-Date with the Newest FeaturesMay 09, 2025 am 12:03 AM

Laravel's latest version is 10.x, released in early 2023. This version brings enhanced EloquentORM functionality and a simplified routing system, improving development efficiency and performance, but it needs to be tested carefully during upgrades to prevent problems.

Mastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMay 08, 2025 am 12:25 AM

Laravelsoftdeletesallow"deletion"withoutremovingrecordsfromthedatabase.Toimplement:1)UsetheSoftDeletestraitinyourmodel.2)UsewithTrashed()toincludesoft-deletedrecordsinqueries.3)CreatecustomscopeslikeonlyTrashed()forstreamlinedcode.4)Impleme

Laravel Soft Deletes: Restoring and Permanently Deleting RecordsLaravel Soft Deletes: Restoring and Permanently Deleting RecordsMay 08, 2025 am 12:24 AM

In Laravel, restore the soft deleted records using the restore() method, and permanently delete the forceDelete() method. 1) Use withTrashed()->find()->restore() to restore a single record, and use onlyTrashed()->restore() to restore a single record. 2) Permanently delete a single record using withTrashed()->find()->forceDelete(), and multiple records use onlyTrashed()->forceDelete().

The Current Laravel Release: Download and Upgrade Today!The Current Laravel Release: Download and Upgrade Today!May 08, 2025 am 12:22 AM

You should download and upgrade to the latest Laravel version as it provides enhanced EloquentORM capabilities and new routing features, which can improve application efficiency and security. To upgrade, follow these steps: 1. Back up the current application, 2. Update the composer.json file to the latest version, 3. Run the update command. While some common problems may be encountered, such as discarded functions and package compatibility, these issues can be solved through reference documentation and community support.

Laravel: When should I update to the last version?Laravel: When should I update to the last version?May 08, 2025 am 12:18 AM

YoushouldupdatetothelatestLaravelversionwhenthebenefitsclearlyoutweighthecosts.1)Newfeaturesandimprovementscanenhanceyourapplication.2)Securityupdatesarecrucialifvulnerabilitiesareaddressed.3)Performancegainsmayjustifyanupdateifyourappstruggles.4)Ens

See all articles

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

Safe Exam Browser

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.