Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the queue mechanism of Laravel

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to use the queue mechanism of Laravel, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand.

Why would you do that?

First of all, we need to know why we use queues and what happens without queues! What are the advantages and disadvantages?

We can give examples of a few simple scenarios.

Send mail

What problems do you generally face in sending mail?

Send slowly

Failed to send

The sending frequency is too high, rejected by the service provider or put into the dustbin.

What are the advantages of using queues?

Improve client response

When sending, we do not deal with 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 according to the configuration.

Improve fault tolerance

In the process of sending, we may encounter that the target is rejected. For example, most people will encounter the scenario of sending an error 502 to admin@qq.comn. Well, this kind of scenario, we can understand that it is an event. In the process of sending an email, we can trigger the following events.

Sending this email may lead to multiple time-consuming tasks, so we can actually build multiple queue services. Each queue manages its own things and decouples them well.

Through the Laravel queue, you can set up immediate sending, delayed sending, and retrying sending.

Failed to send

Mail records are stored in the warehouse.

Code exception

Callback for successful delivery of email

Failed to send and retry

The transmission frequency is controllable.

Developers who have used bulk emails are bound to encounter a problem, that is, if we send them directly in bulk, that is, a large number of emails are sent at the same time. Well, the mail service provider is likely to reject our mail or put it into the dustbin and be identified as advertising. then, delayed delivery is used here. We can use the mail that is known to be waiting for delivery in the current queue service. Reasonable configuration frequency, or switch mail configuration, to achieve, frequency can be controlled.

Such as setting a configuration to send 10 times a minute, and so on. Similarly, we can decouple configuration, frequency control and transmission control here.

Other

Of course, there are many other situations that we will use.

Download excel on server side

Server-side asynchronous multitasking big data

Error message handling

How to use Laravel queues

Here is just a list of the general direction of use, and how to better use it. The code may not be able to run, mainly to understand the logic. We use Redis as the driver here.

The driver is set to Redis

> .envQUEUE _ CONNECTION=redis > can be found in config/queue.php

Quickly create queues and delivery tasks

# create Task php artisan make:job ProcessPodcast

Automatically generate 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 (); / / Check the currently available Mailer / / you can customize it here. In this method, you can get the currently available configuration $mailer = $service- > getMailer () according to your own configuration; / /. Get the data currently to be sent $data = $this- > data; $service- > send ($mailer, $data);}} some common operations

These operations can be found in the documentation.

Call to send

# delay sending by 2 minutes # Crontab packet is used here (but Laravel comes with it) EmailJob::dispatch ()-> delay (now ()-> addMinutes (2)); # send immediately (will not enter the queue) EmailJob::dispatchNow ()

The queue here uses the defult queue by default. We can modify it to specify the queue service.

Public function _ _ construct (array $data) {# use emailQueue $this- > onQueue ('emailQueue'); $this- > data = $data;}

Set the number of retries in case of failure

# retry 5 times public $tries = 5

Set the timeout

/ * determine how long a task should time out * * @ return\ DateTime*/public function retryUntil () {return now ()-> addMinutes (10);}

Start our queue

If you do not configure onQueue, you can configure it without the-queue parameter

Php artisan queue:work-queue=emailQueue combined with Events to decouple

Laravel Event is also implemented through queues.

# create Eventphp artisan make:event FailEventclass FailEvent {use Dispatchable, InteractsWithSockets, SerializesModels; protected $data; protected $tag; / * @ param array $data delivered data * @ param string $tag to operate * / public function _ _ construct (array $data, string $tag = 'system') {$this- > data = $data; $this- > tag = $tag Create listener php artisan make:listener FailListenerclass FailListener {/ * Handle the event. * * @ param object $event * @ return void * / public function handle (FailEvent $event) {$this- > {$event- > tag} ($event- > data) } / * handling system exceptions * DateTime: 11:02 on 2021-12-3 * @ param array $data * / public function system (array $data) {} / * * handling mail exceptions * DateTime: 11:02 on 2021-12-3 * / public function email () {}} # app/Providers/EventServiceProvider. Phpprotected $listen = [FailEvent::class = > [FailListener::class] ],] # delivery event (new FailEvent (['error' =' exception message'], 'email')) Other

In fact, most of the Laravel helped me to implement the whole process. You can try to implement a controllable queue using redis yourself. Proficiency is to master the relevant data types of Redis. Here is a brief list of the data types that will be used in the above schema in Redis

List

It can be used to complete the queue function of going out of the stack and into the stack.

Hash

Try not to serialize the entire class by using the data that he can use to store the serialized Event or Job _ _ construct.

You can also store Mailer data.

Sorted Set

You can set the time to the score in Sorted Set, and sort the scores to find the queue tasks we are going to execute recently.

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

There is no perfect solution in the world, only the one that is most suitable for you. If you encounter problems in your work, try to learn to use a variety of tools and designs to achieve them. The code is just a microcosm of the end, and you have to learn to understand that each language and every framework is only an implementation of a solution.

Thank you for reading this article carefully. I hope the article "how to use the queue Mechanism of Laravel" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report