Home>Article>PHP Framework> Let’s talk about Laravel’s queue mechanism and understand the usage scenarios of queues.

Let’s talk about Laravel’s queue mechanism and understand the usage scenarios of queues.

青灯夜游
青灯夜游 forward
2021-12-20 16:52:49 2475browse

How to use Laravel queue? Below, theLaraveltutorial column will introduce to you how to use Laravel queues, as well as scenarios for using queues. I hope it will be helpful to you!

Let’s talk about Laravel’s queue mechanism and understand the usage scenarios of queues.

Why?

First of all, we need to know why we need to use queues, and what will happen if we don’t use queues! What are the advantages and disadvantages

We can give some examples of simple scenarios.

Sending emails

What are the common problems faced when sending emails??

  • Slow sending
  • Failed to send
  • The sending frequency is too high, and it is rejected by the service provider or entered into the trash box

What are the benefits of using a queue?

  • Improve client response

    When sending, we do not process it immediately, but throw it to the server, and the queue is managed and scheduled. You can customize the option to send immediately or delay sending according to the configuration

  • Improve fault tolerance

    During the sending process, we may encounter that the target is rejected. For example, most people will encounter the scenario of sending error 502 toadmin@qq.comn. In this scenario, we can understand this scenario as an event. During the process of email sending, we can trigger and construct the following events

    • Sending failure
    • Email record storage
    • Code exception
    • Callback for successful email sending
    • Retry if sending fails

    Sending through this email may Leading to the generation of multiple time-consuming tasks, we can actually build multiplequeue services. Each queue manages its own affairs, very gooddecouplingThey

    can be set very well through the Laravel queueimmediate sending,delayed sending,Retry sending

  • Sending frequency is controllable

    Developers who have used emails sent in batches will inevitably encounter a problem. That is, if we directly send in batches, that is, send a large number of emails at the same time. Then the email service provider is likely to reject our email orthe email will be put into the trashand be identified asadvertisementSo,delayed sendingis used here , we can configure the frequency reasonably according to the known mails waiting for delivery in the current queue service, or switch the mail configuration to achieve controllable frequency.

    Such as setting a configuration to be sent 10 times a minute, etc. Similarly, we can achieveconfiguration, frequency control, and transmission control decoupling here

##Others

Of course we still have many situations where we will use it

    Server-side downloading excel
  • Server-side asynchronous multitasking of big data
  • Error message processing

How to use Laravel queue

Here is just a list of general usage directions and how to use it better . The code may not run well, the main thing is to understand the logic We are using Redis as the driver here

The driver is set to Redis

> .env QUEUE_CONNECTION=redis > 在 config/queue.php 中可以找到

Quickly create queues and Delivery task

# 创建 任务 php artisan make:job ProcessPodcast

Automatic generation

app/Jobs/EmailJob.php

class EmailJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $data; /** * Create a new job instance. * * @return void */ public function __construct(array $data) { $this->data = $data; } /** * Execute the job. * * @return void */ public function handle() { $service = new EmailService(); // ... 检查当前可用 Mailer // 这里你自定义就好了,这个方法中你可以根据你自己的配置,获取到当前可用的配置 $mailer = $service->getMailer(); // ... 获取当前要发送的数据 $data = $this->data; $service->send($mailer, $data); } }

Some common operations

These operations can be found in the document

Call to send

# 延迟 2分钟 发送 # 这里使用的是 Crontab 包 (不过 Laravel 自带) EmailJob::dispatch()->delay(now()->addMinutes(2)); # 立即发送 (不会进入到队列中) EmailJob::dispatchNow();

The queue here uses the defult queue by default, and we can modify it to specify the queue service

public function __construct(array $data) { # 使用 emailQueue $this->onQueue('emailQueue'); $this->data = $data; }

Set the number of retries in case of failure

# 重试 5 次 public $tries = 5;

Set the timeout period

/** * 确定任务应该超时的时间 * * @return \DateTime */ public function retryUntil() { return now()->addMinutes(10); }

Start our queue

If you do not configure onQueue, you can With ---queue parameter configuration

php artisan queue:work --queue=emailQueue

Combined with Events to decouple

Laravel Event is also implemented through queue

# 创建 Event php artisan make:event FailEvent class FailEvent { use Dispatchable, InteractsWithSockets, SerializesModels; protected $data; protected $tag; /** * @param array $data 投递的数据 * @param string $tag 要操作的事情 */ public function __construct(array $data, string $tag = 'system') { $this->data = $data; $this->tag = $tag; } } # 创建 listener php artisan make:listener FailListener class FailListener { /** * Handle the event. * * @param object $event * @return void */ public function handle(FailEvent $event) { $this->{$event->tag}($event->data); } /** * 处理系统异常 * DateTime: 2021/12/3 11:02 上午 * @param array $data */ public function system(array $data) { } /** * 处理邮件异常 * DateTime: 2021/12/3 11:02 上午 */ public function email() { } } # app/Providers/EventServiceProvider.php protected $listen = [ FailEvent::class => [ FailListener::class, ], ] # 投递 event(new FailEvent(['error' = '异常信息'], 'email'));

Others

In fact, Laravel mostly helped me implement the entire process. You can try to use redis to implement a controllable queue yourself. Proficiency is all you need to master Redis related data types. Here is a brief list of the data types used in Redis in the above modes

  • List

    Use it to complete the queue function of popping and pushing into the stack

  • Hash

    Use it to store the serialized

    EventorJob__constructpassed For the incoming data, try not to serialize the entire class

    You can also implement storage. Mailer data

  • Sorted Set

    You can set the time to

    Sorted SetSort by the score to find the queue task we want to execute recently

Of course, there are many other uses of Redis to meet your own needs. Can.

There is no perfect solution in the world, only the most suitable solution for you. When you encounter problems at work, try to learn to draw inferences from one example, use various tools reasonably, and design solutions to implement them. The code is just the final microcosm. The final thing is to learn to understand. Each language and each framework is just the implementation of a solution. Only by mastering it can you be invincible...

For more programming-related knowledge, please Visit:Introduction to Programming! !

The above is the detailed content of Let’s talk about Laravel’s queue mechanism and understand the usage scenarios of queues.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete