laravel源碼分析隊列Queue方法示例
前言
隊列 (Queue) 是 laravel 中比較常用的一個功能,隊列的目的是將耗時的任務延時處理,比如發(fā)送郵件,從而大幅度縮短 Web 請求和響應的時間。本文我們就來分析下隊列創(chuàng)建和執(zhí)行的源碼。
隊列任務的創(chuàng)建
先通過命令創(chuàng)建一個 Job 類,成功之后會創(chuàng)建如下文件 laravel-src/laravel/app/Jobs/DemoJob.php。
> php artisan make:job DemoJob > Job created successfully.
下面我們來分析一下 Job 類的具體生成過程。
執(zhí)行 php artisan make:job DemoJob
后,會觸發(fā)調用如下方法。
laravel-src/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
/** * Register the command. * [A] make:job 時觸發(fā)的方法 * @return void */ protected function registerJobMakeCommand() { $this->app->singleton('command.job.make', function ($app) { return new JobMakeCommand($app['files']); }); }
接著我們來看下 JobMakeCommand 這個類,這個類里面沒有過多的處理邏輯,處理方法在其父類中。
?class JobMakeCommand extends GeneratorCommand
我們直接看父類中的處理方法,GeneratorCommand->handle(),以下是該方法中的主要方法。
public function handle() { // 獲取類名 $name = $this->qualifyClass($this->getNameInput()); // 獲取文件路徑 $path = $this->getPath($name); // 創(chuàng)建目錄和文件 $this->makeDirectory($path); // buildClass() 通過模板獲取新類文件的內容 $this->files->put($path, $this->buildClass($name)); // $this->type 在子類中定義好了,例如 JobMakeCommand 中 type = 'Job' $this->info($this->type.' created successfully.'); }
方法就是通過目錄和文件,創(chuàng)建對應的類文件,至于新文件的內容,都是基于已經(jīng)設置好的模板來創(chuàng)建的,具體的內容在 buildClass($name) 方法中。
?protected function buildClass($name) { // 得到類文件模板,getStub() 在子類中有實現(xiàn),具體看 JobMakeCommand $stub = $this->files->get($this->getStub()); // 用實際的name來替換模板中的內容,都是關鍵詞替換 return $this->replaceNamespace($stub, $name)->replaceClass($stub, $name); }
獲取模板文件
protected function getStub() { return $this->option('sync') ? __DIR__.'/stubs/job.stub' : __DIR__.'/stubs/job-queued.stub'; }
job.stub
?<?php /** * job 類的生成模板 */ namespace DummyNamespace; use Illuminate\Bus\Queueable; use Illuminate\Foundation\Bus\Dispatchable; class DummyClass { use Dispatchable, Queueable; /** * Create a new job instance. * * @return void */ public function __construct() { // } /** * Execute the job. * * @return void */ public function handle() { // } }
job-queued.stub
<?php /** * job 類的生成模板 */ namespace DummyNamespace; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; class DummyClass implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. * * @return void */ public function __construct() { // } /** * Execute the job. * * @return void */ public function handle() { // } }
下面看一下前面我們創(chuàng)建的一個Job類,DemoJob.php,就是來源于模板 job-queued.stub。
<?php /** * job 類的生成模板 */ namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; class DemoJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. * * @return void */ public function __construct() { // } /** * Execute the job. * * @return void */ public function handle() { // } }
至此,我們已經(jīng)大致明白了隊列任務類是如何創(chuàng)建的了。下面我們來分析下其是如何生效運行的。
隊列任務的分發(fā)
任務類創(chuàng)建后,我們就可以在需要的地方進行任務的分發(fā),常見的方法如下:
DemoJob::dispatch(); // 任務分發(fā) DemoJob::dispatchNow(); // 同步調度,隊列任務不會排隊,并立即在當前進程中進行
下面先以 dispatch() 為例分析下分發(fā)過程。
trait Dispatchable { public static function dispatch() { return new PendingDispatch(new static(...func_get_args())); } }
?class PendingDispatch { protected $job; public function __construct($job) { echo '[Max] ' . 'PendingDispatch ' . '__construct' . PHP_EOL; $this->job = $job; } public function __destruct() { echo '[Max] ' . 'PendingDispatch ' . '__destruct' . PHP_EOL; app(Dispatcher::class)->dispatch($this->job); } }
重點是 app(Dispatcher::class)->dispatch($this->job) 這部分。
我們先來分析下前部分 app(Dispatcher::class),它是在 laravel 框架中自帶的 BusServiceProvider 中向 $app 中注入的。
class BusServiceProvider extends ServiceProvider implements DeferrableProvider { public function register() { $this->app->singleton(Dispatcher::class, function ($app) { return new Dispatcher($app, function ($connection = null) use ($app) { return $app[QueueFactoryContract::class]->connection($connection); }); }); } }
看一下 Dispatcher 的構造方法,至此,我們已經(jīng)知道前半部分 app(Dispatcher::class) 是如何來的了。
class Dispatcher implements QueueingDispatcher { protected $container; protected $pipeline; protected $queueResolver; public function __construct(Container $container, Closure $queueResolver = null) { $this->container = $container; /** * Illuminate/Bus/BusServiceProvider.php->register()中 * $queueResolver 傳入的是一個閉包 * function ($connection = null) use ($app) { * return $app[QueueFactoryContract::class]->connection($connection); * } */ $this->queueResolver = $queueResolver; $this->pipeline = new Pipeline($container); } public function dispatch($command) { if ($this->queueResolver && $this->commandShouldBeQueued($command)) { // 將 $command 存入隊列 return $this->dispatchToQueue($command); } return $this->dispatchNow($command); } }
BusServiceProvider 中注冊了 Dispatcher::class ,然后 app(Dispatcher::class)->dispatch($this->job) 調用的即是 Dispatcher->dispatch()。
?public function dispatchToQueue($command) { // 獲取任務所屬的 connection $connection = $command->connection ?? null; /* * 獲取隊列實例,根據(jù)config/queue.php中的配置 * 此處我們配置 QUEUE_CONNECTION=redis 為例,則獲取的是RedisQueue * 至于如何通過 QUEUE_CONNECTION 的配置獲取 queue ,此處先跳過,本文后面會具體分析。 */ $queue = call_user_func($this->queueResolver, $connection); if (! $queue instanceof Queue) { throw new RuntimeException('Queue resolver did not return a Queue implementation.'); } // 我們創(chuàng)建的DemoJob無queue方法,則不會調用 if (method_exists($command, 'queue')) { return $command->queue($queue, $command); } // 將 job 放入隊列 return $this->pushCommandToQueue($queue, $command); } protected function pushCommandToQueue($queue, $command) { // 在指定了 queue 或者 delay 時會調用不同的方法,基本大同小異 if (isset($command->queue, $command->delay)) { return $queue->laterOn($command->queue, $command->delay, $command); } if (isset($command->queue)) { return $queue->pushOn($command->queue, $command); } if (isset($command->delay)) { return $queue->later($command->delay, $command); } // 此處我們先看最簡單的無參數(shù)時的情況,調用push() return $queue->push($command); }
筆者的配置是 QUEUE_CONNECTION=redis ,估以此來分析,其他類型的原理基本類似。
配置的是 redis 時, $queue 是 RedisQueue 實例,下面我們看下 RedisQueue->push() 的內容。
Illuminate/Queue/RedisQueue.php
public function push($job, $data = '', $queue = null) { /** * 獲取隊列名稱 * var_dump($this->getQueue($queue)); * 創(chuàng)建統(tǒng)一的 payload,轉成 json * var_dump($this->createPayload($job, $this->getQueue($queue), $data)); */ // 將任務和數(shù)據(jù)存入隊列 return $this->pushRaw($this->createPayload($job, $this->getQueue($queue), $data), $queue); } public function pushRaw($payload, $queue = null, array $options = []) { // 寫入redis中 $this->getConnection()->eval( LuaScripts::push(), 2, $this->getQueue($queue), $this->getQueue($queue).':notify', $payload ); // 返回id return json_decode($payload, true)['id'] ?? null; }
至此,我們已經(jīng)分析完了任務是如何被加入到隊列中的。
以上就是laravel源碼分析隊列Queue方法示例的詳細內容,更多關于laravel源碼分析隊列Queue方法的資料請關注腳本之家其它相關文章!
相關文章
PHP函數(shù)import_request_variables()用法分析
這篇文章主要介紹了PHP函數(shù)import_request_variables()用法,結合實例形式分析了import_request_variables函數(shù)的功能,定義及相關使用技巧,需要的朋友可以參考下2016-04-04通過php動態(tài)傳數(shù)據(jù)到highcharts
本文主要介紹了通過php動態(tài)傳數(shù)據(jù)到highcharts的相關知識。具有很好的參考價值。下面跟著小編一起來看下吧2017-04-04PHP實現(xiàn)創(chuàng)建微信自定義菜單的方法示例
這篇文章主要介紹了PHP實現(xiàn)創(chuàng)建微信自定義菜單的方法,結合實例形式分析了php創(chuàng)建微信自定義菜單的原理、步驟與具體實現(xiàn)技巧,需要的朋友可以參考下2017-07-07