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

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

See all articles