如何減少 Hyperf 框架的掃描時間

李銘昕發表於2020-04-07

原因

Hyperf 框架為了防止使用者更新元件後,代理快取沒有更新導致啟動報錯。增加了以下鉤子。

{
    "scripts": {
        "post-autoload-dump": [
            "init-proxy.sh"
        ]
    }
}

init-proxy.sh 指令碼,會執行 php bin/hyperf.php di:init-proxy 命令清理代理快取,並重新生成。

$ composer init-proxy
> init-proxy.sh
../../
Runtime cleared
Scanning app ...
Scan app completed, took 195.76692581177 milliseconds.
Scanning vendor ...
Scan vendor completed, took 510.0839138031 milliseconds.
This command does not clear the runtime cache, If you want to delete them, use `vendor/bin/init-proxy.sh` instead.
Proxy class create success.
Finish!

上述演示中,我們很清楚的可以看到花費的時間,現在不足 1s 其實還可以接受。但如果您的模型非常多,這個時間可能會是無法忍受的一個點。比如以下情況。

$ composer init-proxy
> init-proxy.sh
../../
Runtime cleared
Scanning app ...
Scan app completed, took 3063.5998249054 milliseconds.
Scanning vendor ...
Scan vendor completed, took 490.39006233215 milliseconds.
This command does not clear the runtime cache, If you want to delete them, use `vendor/bin/init-proxy.sh` instead.
Proxy class create success.
Finish!

解決辦法

以下解決辦法建立在正確使用 Model 的基礎上。比如不在 Model 中使用註解。檢測辦法是,不排除 Model 目錄的情況下生成一下代理快取,檢視是否生成 Model 相關的代理。

所以,我們可以主動修改 Hyperf 框架的掃描目錄,排除掉模型目錄。讓我們寫一段邏輯,修改 annotations.php

<?php

declare(strict_types=1);

use Symfony\Component\Finder\Finder;

return [
    'scan' => [
        'paths' => value(function () {
            $paths = [];
            $dirs = Finder::create()->in(BASE_PATH . '/app')
                ->depth('< 1')
                ->exclude(['Model']) // 此處按照實際情況進行修改
                ->directories();
            /** @var SplFileInfo $dir */
            foreach ($dirs as $dir) {
                $paths[] = $dir->getRealPath();
            }
            return $paths;
        }),
        'ignore_annotations' => [
            'mixin',
        ],
    ],
];

當我們再執行命令時,就會發現時間被大大縮短。

寫在最後

Hyperf 是基於 Swoole 4.4+ 實現的高效能、高靈活性的 PHP 協程框架,內建協程伺服器及大量常用的元件,效能較傳統基於 PHP-FPM 的框架有質的提升,提供超高效能的同時,也保持著極其靈活的可擴充套件性,標準元件均基於 PSR 標準 實現,基於強大的依賴注入設計,保證了絕大部分元件或類都是 可替換 與 可複用 的。

框架元件庫除了常見的協程版的 MySQL 客戶端、Redis 客戶端,還為您準備了協程版的 Eloquent ORM、WebSocket 服務端及客戶端、JSON RPC 服務端及客戶端、GRPC 服務端及客戶端、Zipkin/Jaeger (OpenTracing) 客戶端、Guzzle HTTP 客戶端、Elasticsearch 客戶端、Consul 客戶端、ETCD 客戶端、AMQP 元件、Apollo 配置中心、阿里雲 ACM 應用配置管理、ETCD 配置中心、基於令牌桶演算法的限流器、通用連線池、熔斷器、Swagger 文件生成、Swoole Tracker、Blade 和 Smarty 檢視引擎、Snowflake 全域性ID生成器 等元件,省去了自己實現對應協程版本的麻煩。

Hyperf 還提供了 基於 PSR-11 的依賴注入容器、註解、AOP 面向切面程式設計、基於 PSR-15 的中介軟體、自定義程式、基於 PSR-14 的事件管理器、Redis/RabbitMQ 訊息佇列、自動模型快取、基於 PSR-16 的快取、Crontab 秒級定時任務、Translation 國際化、Validation 驗證器 等非常便捷的功能,滿足豐富的技術場景和業務場景,開箱即用。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

相關文章