Table of Contents
redis queue data structure
List linked list
Zset ordered set
Laravel Queue Service Task Scheduling
The overall process of laravel queue service
Create task
queue settings
Creation of task class
Home PHP Framework Laravel Introduction to the usage of queues in laravel framework (with code)

Introduction to the usage of queues in laravel framework (with code)

Aug 28, 2018 pm 01:37 PM
laravel php redis

This article brings you an introduction to the usage of queues in the laravel framework (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In actual project development, we often encounter situations that require lightweight queues, such as sending text messages, sending emails, etc. These tasks are not enough to use heavyweight message queues such as kafka and RabbitMQ, but And it does require functions such as asynchronous, retry, and concurrency control. Generally speaking, we often use Redis, Beanstalk, and Amazon SQS to implement related functions. Laravel provides a unified API for different background queue services. This article will introduce the most widely used redis queue.

Before explaining laravel’s queue service, we must first talk about the queue service based on redis. First of all, redis is designed for caching, but due to some of its own characteristics, it can be used for message queues

redis queue data structure

List linked list

redis It is easy to implement message queue features such as FIFO (first in, first out). You only need a list object to fetch data from the beginning and stuff data from the tail.

Related commands: (1) Left-side input and right-side output: lpush/rpop; (2) Right-side input and left-side output: rpush/lpop.

This simple message queue is easy to implement.

Zset ordered set

Some task scenarios do not require the task to be executed immediately, but need to be delayed; some tasks are very important and need to be retried when the task fails. These functions cannot be accomplished solely by relying on lists. At this time, an ordered collection of redis is needed.

Redis ordered set is similar to Redis set, which is a collection that does not contain the same string. The difference between them is that each member of the ordered set is associated with a score, which is used to rank the members of the ordered set from the lowest score to the highest score.

There is no relationship between the ordered set and the delayed task. However, you can set the score of the ordered set to the time when the delayed task is started, and then poll the ordered set to retrieve the expired tasks. Come out for processing, thus realizing the function of delaying tasks.

For important tasks that need to be retried, before the task is executed, the task will be put into an ordered collection and the longest execution time of the task will be set. If the task is successfully executed, the task will be deleted from the ordered collection. If the task is not completed within the specified time, the tasks in the ordered set will be put back into the queue.

Related commands:

(1) ZADD Adds one or more members to an ordered set, or updates its score if it already exists.

(2) ZRANGEBYSCORE Returns an ordered set of member ranges by score.

(3) ZREMRANGEBYRANK Removes all members from an ordered set within the given index.

Laravel Queue Service Task Scheduling

The queue service task scheduling process is as follows:

Introduction to the usage of queues in laravel framework (with code)

Laravel’s queue service consists of two There are two process controls, one is the producer and the other is the consumer. These two processes manipulate three redis queues, one of which is List, responsible for immediate tasks, and two Zsets, responsible for delayed tasks and pending tasks.

The producer is responsible for pushing tasks to redis. If it is an immediate task, it will be pushed to queue:default by default; if it is a delayed task, it will be pushed to queue:default:delayed.

The consumer polls two queues, continuously takes out tasks from the queue, first puts the tasks into queue:default:reserved, and then executes related tasks. If the task is executed successfully, the task in queue:default:reserved will be deleted, otherwise it will be put back into the queue:default:delayed queue.

The overall process of laravel queue service

Task distribution process:

Introduction to the usage of queues in laravel framework (with code)

Task processor operation:

Introduction to the usage of queues in laravel framework (with code)

Create task

queue settings

1

2

3

4

5

6

'redis' => [

        'driver' => 'redis',

        'connection' => 'default',

        'queue' => 'default',

        'retry_after' => 90,

    ],

Copy after login

Configure in config/queue.php
Generally speaking, the default redis configuration As above, connection is the connection name of redis in the database; queue is the queue name in redis. It is worth noting that if you are using a redis cluster, you need to use the key hash tag, which is {default}; when the task runs beyond retry_after After this time, the task will be put back into the queue.

Creation of task class

The structure of the task class is very simple. Generally speaking, it only contains a handle method that the queue uses to call this task.

If you want the task to be pushed to the queue rather than executed synchronously, you need to implement the IlluminateContractsQueueShouldQueue interface.

If you want to push tasks to a specific connection, such as redis or sqs, you need to set the conneciton variable.

If you want to push the task to a specific queue, you can set the queue variable.

如果想要让任务延迟推送,那么需要设置 delay 变量。

如果想要设置任务至多重试的次数,可以使用 tries 变量;

如果想要设置任务可以运行的最大秒数,那么可以使用 timeout 参数。

如果想要手动访问队列,可以使用 trait : IlluminateQueueInteractsWithQueue。

任务的分发
分发服务
写好任务类后,就能通过 dispatch 辅助函数来分发它了。唯一需要传递给 dispatch 的参数是这个任务类的实例:

1

2

3

4

5

6

7

8

9

class PodcastController extends Controller

{

    public function store(Request $request)

    {

        // 创建播客...

 

        ProcessPodcast::dispatch($podcast);

    }

}

Copy after login

如果想延迟执行一个队列中的任务,可以用任务实例的 delay 方法。

1

2

 ProcessPodcast::dispatch($podcast)

                ->delay(Carbon::now()->addMinutes(10));

Copy after login

通过推送任务到不同的队列,可以给队列任务分类,甚至可以控制给不同的队列分配多少任务。要指定队列的话,就调用任务实例的 onQueue 方法:

1

ProcessPodcast::dispatch($podcast)->onQueue('processing');

Copy after login

如果使用了多个队列连接,可以将任务推到指定连接。要指定连接的话,可以在分发任务的时候使用 onConnection 方法:

1

2

ProcessPodcast::dispatch($podcast)->onConnection('redis

');

Copy after login

The above is the detailed content of Introduction to the usage of queues in laravel framework (with code). 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the difference between php framework laravel and yii What is the difference between php framework laravel and yii Apr 30, 2025 pm 02:24 PM

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

Recommended Laravel's best expansion packs: 2024 essential tools Recommended Laravel's best expansion packs: 2024 essential tools Apr 30, 2025 pm 02:18 PM

The essential Laravel extension packages for 2024 include: 1. LaravelDebugbar, used to monitor and debug code; 2. LaravelTelescope, providing detailed application monitoring; 3. LaravelHorizon, managing Redis queue tasks. These expansion packs can improve development efficiency and application performance.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

Laravel logs and error monitoring: Sentry and Bugsnag integration Laravel logs and error monitoring: Sentry and Bugsnag integration Apr 30, 2025 pm 02:39 PM

Integrating Sentry and Bugsnag in Laravel can improve application stability and performance. 1. Add SentrySDK in composer.json. 2. Add Sentry service provider in config/app.php. 3. Configure SentryDSN in the .env file. 4. Add Sentry error report in App\Exceptions\Handler.php. 5. Use Sentry to catch and report exceptions and add additional context information. 6. Add Bugsnag error report in App\Exceptions\Handler.php. 7. Use Bugsnag monitoring

See all articles