laravel队列调用队列_为什么Laravel队列很棒

laravel队列调用队列

Laravel was the fastest tool I learned and I did that in a week with just a basic knowledge of PHP. Do not get me wrong but it was quite ironical to me. I saw my self as a C# master back in the days until I picked up ASP.Net and lost 15% of my weight in the first week learning it with all seriousness.

Laravel是我学到的最快的工具,我仅用PHP的基本知识就能在一周内做到这一点。 别误会我的意思,但这对我很讽刺。 直到我拿起ASP.Net并在第一周认真学习所有体重的15%的体重后,我就将自己视为C#大师。

I only knew the basics of PHP before picking up Laravel and it was so simple I practiced with popcorn on my desk.

在拿起Laravel之前,我只了解PHP的基础知识,这是如此简单,所以我在桌上练习爆米花。

One of the reasons why it is so easy to use, is not because of the simplicity of the language it was built with which is PHP but the amount of love and care, I repeat, love and care put in to make Laravel. When I listened to Jefferey at a Laracon conference, he used the same word, care. I was questioning my subconscious on how code is written with care but by the end of his presentation I got his point.

它之所以如此易于使用的原因之一,并不是因为它所使用的语言是PHP的简单性,而是因为我重复了爱与关怀的程度,从而使Laravel变得更加重要。 当我在一次Laracon会议上听杰弗里( Jefferey)时 ,他用了同样的词,小心。 我在询问下意识者如何谨慎编写代码,但在他的演讲结束时,我明白了他的意思。

Otwell took his time to build Laravel and it's documentation and one of the major features that really amaze me is what we are going to experiment with, Queues.

Otwell花了很多时间来构建Laravel及其文档,而让我真正惊奇的主要功能之一就是我们将要尝试的Queues

Queues in Laravel are used to make a smooth sailing application cycle by stacking heavy tasks to be handled as jobs and dispatching these jobs when it is asked to or when it does not disrupt the user's experience.

Laravel中的队列用于通过堆叠要作为作业处理的繁重任务并在需要时或在不中断用户体验的情况下分派这些作业,从而使应用程序运行顺畅。

Let's assume you have a 12 year old kid named Bill and you decide to send him to a store across the road. At the same time Uncle A is asking him to get him some water and Uncle B is requesting a pen from him. That's not all; his dog Spike wants some food urgently. Bill has to complete all these tasks.

假设您有一个12岁的孩子,名为Bill,您决定将他送到马路对面的一家商店。 同时,A叔叔要他给他喝水,B叔叔要他给我一支笔。 那不是全部; 他的狗狼狗斯派克急切需要一些食物。 比尔必须完成所有这些任务。

As Bill's dad/mum, if you let Bill run off to those tasks at once, he might leave some stones un-turned, get heavily exhausted or end up in an ugly mood. The best thing to do is to give him a list of those tasks and let him check them off one after the other according to priority which is obviously better. This scenario is the concept behind queues and it is good for handling heavy and tasking jobs like social media posting, email sending, heavy logging, etc.

作为比尔的父亲/妈妈,如果您让比尔立即执行这些任务,他可能会留下一些坚硬的石头,变得精疲力竭或最终变得丑陋。 最好的办法是给他一份这些任务的清单,然后让他根据优先级一个接一个地检查它们,这显然更好。 这种情况是队列背后的概念,非常适合处理繁重且任务繁重的工作,例如社交媒体发布,电子邮件发送,繁重的日志记录等。

I will take you through the simple steps of using queues by creating a demo. The demo will be a basic email sending app that sends email at the click of a button.

我将通过创建一个演示向您介绍使用队列的简单步骤。 该演示将是一个基本的电子邮件发送应用程序,只需单击一个按钮即可发送电子邮件。

Before we hit the road, refer to Otwell''s documentation for Laravel installation guide.

在我们上路之前,请参阅Otwell的 Laravel安装指南文档

在Laravel中发送电子邮件 ( Sending Emails in Laravel )

Before we jump into queues, let us send emails the normal way, calculate the time taken and then send later with queues and compare the time difference. Speaking of Laravel being simple, if you have never sent a mail with Laravel you are going to be amazed how dead simple it is.

在我们进入队列之前,让我们以正常方式发送电子邮件,计算花费的时间,然后稍后再与队列发送并比较时间差。 说到Laravel的简单性,如果您从未与Laravel发送过邮件,那么您会惊奇地发现它是如此简单。

What we need first is to setup a mail provider for development. A service known as Mailtrap is available for us to use. Mailtrap has a free package that would be just enough for us to work with. Create an account and a sample inbox named Demo Inbox will be created for you. Click on the Demo Inbox and copy the username and password provided to your .env as follows:

我们首先需要设置一个邮件提供程序进行开发。 我们可以使用一种称为Mailtrap的服务。 Mailtrap有一个免费软件包,足以供我们使用。 创建一个帐户,将为您创建一个名为Demo Inbox的示例收件Demo Inbox 。 单击Demo Inbox然后将提供给.env的用户名和密码复制如下:

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=[USERNAME]
MAIL_PASSWORD=[PASSWORD]
MAIL_ENCRYPTION=null
MAIL_FROM=[YOUR@EMAIL.COM]
MAIL_NAME=[YOUR-NAME]

Create a controller using the artisan command to house our index and send action methods:

使用artisan命令创建一个控制器来容纳我们的indexsend操作方法:

php artisan make:controller HomeController

With the Home controller skeleton available, we can flesh it out by adding an index action to serve as our home page:

有了Home控制器骨架后,我们可以通过添加index动作充实它来充实我们的主页:

public function index()
    {
        return view()->make("home.index");
    }

As you can see we are returning a view that does not exist so let us create one named in index.blade.php in resources/view/home:

如您所见,我们返回的视图不存在,因此让我们在resources/view/home中的index.blade.php中创建一个命名的resources/view/home

<div class="container">
    <div class="main">
        <a href="/send" class="btn btn-default">Send Email</a>
    </div>
</div>

We just basically have a bootstrap styled link pointing to /send which we have yet to create.

我们只是基本上有一个引导风格的链接指向/send ,我们尚未创建。

We need 2 routes for this app, / and /send, so let us replace whatever is in the app/Http/routes.php file with:

我们为此应用程序需要2条路由//send ,因此让我们将app/Http/routes.php文件中的内容替换为:

<?php
Route::get('/', 'HomeController@index');
Route::get('/send', 'HomeController@send');

The only thing left for this section is create the send action method with logic to actually send and email. Guess what! it is just 4 lines of codes.

本节剩下的唯一内容是创建具有实际发送和发送电子邮件逻辑的send操作方法。 你猜怎么了! 它只是4行代码。

public function send()
    {
        Log::info("Request cycle without Queues started");
        Mail::send('email.welcome', ['data'=>'data'], function ($message) {

            $message->from('me@gmail.com', 'Christian Nwmaba');

            $message->to('chris@scotch.io');

        });
        Log::info("Request cycle without Queues finished");
    }

The Log facade at the beginning and end will help us calculate when the request was completed. The Mail facade takes 3 arguments;

Log外观的开头和结尾将帮助我们计算请求完成的时间。 Mail门面有3个参数;

  • the content of the email

    电子邮件内容
  • the data to be bound the the email

    要绑定到电子邮件的数据
  • a Closure that gives us the power to customize the email settings

    Closure使我们能够自定义电子邮件设置

You definitely need to import the following dependencies at the top of your controller:

您绝对需要在控制器顶部导入以下依赖项:

use Log;
use Mail;

I guess you are wondering what sort of content is passed as the first argument for Mail. Mail can accept plain text or a view, and we actually passed a HTML view @ resources/views/email/welcome.blade.php:

我猜您想知道哪种内容作为Mail的第一个参数传递。 Mail可以接受纯文本或视图,我们实际上通过了HTML视图@ resources/views/email/welcome.blade.php

<h3>Welcome to Scotch Queue Team</h3>

<p>This is the most patient team in the Scotch community because we like to wait for our turn</p>

<p>This made our friends love us because we always give them time to do other simple tasks before
coming back to do ours</p>

At this point you can go ahead and hit the Send button on the home page. Check your logs at storage/logs/laravel.log and note the time difference.

此时,您可以继续并单击主页上的“发送”按钮。 在storage/logs/laravel.log检查您的日志,并注意时差。

发送带有队列的电子邮件 ( Sending Emails with Queues )

Now to the reason for this tutorial. We are going to see how simple it is to dispatch our emails using queues. Research claims that step-wise approach of learning is better, so let us try it.

现在到本教程的原因了。 我们将看到使用队列发送电子邮件是多么简单。 研究声称逐步学习方法更好,所以让我们尝试一下。

步骤1:配置驱动程序 (Step 1: Configure a Driver)

Drivers are used to manage queues and store pending queues temporarily. You can see a driver as the task list in the Bill's illustration above. We will use database driver for now as our queues are not much but if you have a heavier application consider Amazon, Beanstalkd, Redis, IronMQ, etc. You can find a list of the available drivers in config/queue.php. To create a database driver, we just run two artisan command and that is all:

驱动程序用于管理队列并临时存储挂起的队列。 您可以在上面的条例草案的插图中看到驱动程序作为任务列表。 我们现在将使用database驱动程序,因为我们的队列并不多,但是如果您的应用程序比较重,请考虑使用Amazon,Beanstalkd,Redis,IronMQ等。您可以在config/queue.php找到可用驱动程序的列表。 要创建数据库驱动程序,我们只需运行两个artisan命令,仅此而已:

php artisan queue:table

php artisan migrate

We need to tell Laravel that we want to use database in the .env file :

我们需要告诉Laravel我们要使用.env文件中的database

QUEUE_DRIVER=database

步骤2:建立工作 (Step 2: Create a Job)

Creating a job just takes another artisan command:

创建工作只需要另一个artisan命令:

php artisan make:job SendWelcomeEmail --queued

The command just like make:controller will create a skeleton for us in app/Jobs named SendWelcomeEmail. The file just has one method handle() which we will implement our send email logic.

类似于make:controller的命令将在名为SendWelcomeEmail app/Jobs为我们创建一个框架。 该文件只有一个方法handle() ,我们将实现我们的发送电子邮件逻辑。

步骤3: handle()方法 (Step 3: The handle() Method)

The same exact logic we had in the show action method of the Home controller will be moved to this method and then we inject the Mailer to the method as follows:

我们将在Home控制器的show action方法中使用的完全相同的逻辑移至该方法,然后将Mailer注入该方法,如下所示:

public function handle(Mailer $mailer)
    {
        $mailer->send('email.welcome', ['data'=>'data'], function ($message) {

            $message->from('nwambachristian@gmail.com', 'Christian Nwmaba');

            $message->to('nwambachristian@gmail.com');

        });
    }

You need to import the Mailer service:

您需要导入Mailer服务:

use Illuminate\Contracts\Mail\Mailer;

步骤4:调度/延迟作业 (Step 4: Dispatching/Delaying Jobs)

Now we need to actually tell our HomeController that the job should be executed but as a queue. The send method will be reduced to:

现在,我们实际上需要告诉HomeController该作业应该作为队列执行。 send方法将减少为:

public function send()
    {
         Log::info("Request Cycle with Queues Begins");
        $this->dispatch(new SendWelcomeEmail());
        Log::info("Request Cycle with Queues Ends");
    }

NB: We can inject dependencies to the Job. If we had a user that is stored in our database whose email we need, we can do this: $this->dispatch(new SendWelcomeEmail($user)); Remember we will edit the Job's constructor to achieve the injecting.

注意:我们可以将依赖项注入到Job中。 如果我们有一个存储在数据库中的用户,该用户需要我们的电子邮件,则可以执行以下操作: $this->dispatch(new SendWelcomeEmail($user)); 记住,我们将编辑Job的构造函数以实现注入。

Jobs can also be delayed to a given time as follows:

也可以将作业延迟到给定时间,如下所示:

public function send()
    {
        Log::info("Request Cycle with Queues Begins");
        $this->dispatch((new SendWelcomeEmail())->delay(60 * 5));
        Log::info("Request Cycle with Queues Ends");
    }

We are still logging to determine the time difference in completing the requests.

我们仍在记录以确定完成请求的时间差。

步骤5:收听队列 (Step 5: Listening to Queues)

The last thing to do is listen for queues and dispatch when the time is right:

最后要做的是在适当的时候侦听队列并调度:

php artisan queue:listen database

If you are using a different driver other than database, replace the connection option. You can also omit the database and just run php artisan queue:listen. Artisan will run against the default queue you set in the .env file.

如果您使用database以外的其他驱动程序,请替换connection选项。 您也可以省略database ,只运行php artisan queue:listen 。 Artisan将针对您在.env文件中设置的默认队列运行。

时间差异 ( Time Difference )

From my PC which is an average developer PC, it took averagely 10.5 seconds to complete the request before we used queues.

在我的PC(通常是开发人员PC)上,使用队列之前,平均需要10.5秒才能完成请求。

[2016-02-23 13:43:37] local.INFO: Request cycle without Queues started 
[2016-02-23 13:43:50] local.INFO: Request cycle without Queues finished  

[2016-02-23 13:50:49] local.INFO: Request cycle without Queues started  
[2016-02-23 13:50:57] local.INFO: Request cycle without Queues finished

On the other hand it took 4.3 seconds to complete with queues

另一方面,队列需要4.3秒才能完成

[2016-02-23 13:59:33] local.INFO: Request Cycle with Queues Begins  
[2016-02-23 13:59:37] local.INFO: Request Cycle with Queues Ends  

[2016-02-23 14:03:26] local.INFO: Request Cycle with Queues Begins  
[2016-02-23 14:03:32] local.INFO: Request Cycle with Queues Ends  

[2016-02-23 14:04:05] local.INFO: Request Cycle with Queues Begins  
[2016-02-23 14:04:10] local.INFO: Request Cycle with Queues Ends 

... and just 1 second to complete with delayed queues

...仅需1秒即可完成,并有延迟的队列

[2016-02-23 14:32:26] local.INFO: Request Cycle with Queues Begins  
[2016-02-23 14:32:27] local.INFO: Request Cycle with Queues Ends  

[2016-02-23 14:33:24] local.INFO: Request Cycle with Queues Begins  
[2016-02-23 14:33:25] local.INFO: Request Cycle with Queues Ends  

[2016-02-23 14:34:04] local.INFO: Request Cycle with Queues Begins  
[2016-02-23 14:34:05] local.INFO: Request Cycle with Queues Ends  

You can see am not bluffing here, we have facts. Imagine you are to send a mail to a 1000 customers.

您可以看到这里没有虚张声势,我们有事实。 假设您要向1000位客户发送邮件。

使用演示 ( Using the Demo )

Scotch will always give you a demo when you need one. The Demo Repository has 3 branches, a master, beforeQueues and afterQueues. Clone the repository and checkout to beforeQueues or afterQueues to preview the examples. The master branch is empty with Laravel skeleton.

当您需要演示时,Scotch将始终为您提供演示。 演示存储库具有3个分支,即masterbeforeQueuesafterQueues 。 克隆存储库,并检出到beforeQueuesafterQueues以预览示例。 Laravel骨架的master分支是空的。

最后的话 ( Final Words )

It will definitely be a good idea if you incorporate queues in your future projects for tasks like mail sending, social media sharing, social media posting, etc. With this you will be giving your users that experience they deserve and make them come back. At the same time, you'll be giving your server a nice treat.

如果您将队列纳入邮件发送,社交媒体共享,社交媒体发布等任务的未来项目中,绝对是一个好主意。通过这样做,您将为用户提供应有的体验并让他们回来。 同时,您将为服务器提供不错的待遇。

Update (March 21, 2016): Updated Mailtrap's broken link

更新(2016年3月21日):更新了邮件陷阱的断开链接

翻译自: https://scotch.io/tutorials/why-laravel-queues-are-awesome

laravel队列调用队列

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值