hyperf| hyperf 源碼解讀 2: start

date: 2019-08-19 23:03:15
title: hyperf| hyperf 源碼解讀 2: start

上篇我們跟著 php bin/hyperf.php 命令, 看到了框架的核心 container, 這篇我們跟著 php bin/hyperf.php start, 來會一會強大到爆炸的 swoole

開始之前, 請確保自己具備一定的 swoole 基礎知識, 這篇適合你:

千萬不要小看了 基礎知識, 與其一直卡殼浪費時間, 不如沉下心來好好讀一下 swoole wiki, 看似 艱辛, 絕對比沒有這些基礎知識導致的時間浪費要劃算得多得多得多 !

Command 基礎

從上一篇的 blog 可知, hyperf 源碼解讀 1: 啟動, php bin/hyperf.php 執(zhí)行的命令, 是基于 Symfony\Component\Console\Application 提供的命令行應用提供的功能, 初始內置的 command, 是有 ConfigProvider 配置項中的 command 字段設置的. 那么, 我們將要執(zhí)行的 start 命令, 是由哪個 command 提供的呢?

可以根據(jù) gen:command 命令生成的 demo 代碼, 了解到:

// \App\Command\TestCommand
public function __construct(ContainerInterface $container)
{
    $this->container = $container;

    // 命令的名字通常在這里配置
    parent::__construct('t');
}

對應的 start 命令, 就可以通過全局搜索 parent::__construct('start') 查詢到

搜索是很重要的能力, 甚至可以上升到 搜商. 你并不需要特別熟悉一個事物, 但是你依舊有 能力 進行處理, 搜商就是這樣的一個基礎能力. 閱讀源碼也是提高搜商的一個有力方法.

OK, 就定位到了我們 start 命令對應的代碼: \Hyperf\Server\Command\StartServer

StartServer 一覽

/**
 * @Command
 */
class StartServer extends SymfonyCommand
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        parent::__construct('start');
        $this->container = $container;

        $this->setDescription('Start swoole server.');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        \Swoole\Runtime::enableCoroutine(true);

        $this->checkEnvironment($output);

        $serverFactory = $this->container->get(ServerFactory::class)
            ->setEventDispatcher($this->container->get(EventDispatcherInterface::class))
            ->setLogger($this->container->get(StdoutLoggerInterface::class));

        $serverConfig = $this->container->get(ConfigInterface::class)->get('server', []);
        if (! $serverConfig) {
            throw new \InvalidArgumentException('At least one server should be defined.');
        }

        $serverFactory->configure($serverConfig);
        $serverFactory->start();
    }

    private function checkEnvironment(OutputInterface $output)
    {
        if (ini_get_all('swoole')['swoole.use_shortname']['local_value'] !== 'Off') {
            $output->writeln('<error>ERROR</error> Swoole short name have to disable before start server, please set swoole.use_shortname = \'Off\' into your php.ini.');
            exit(0);
        }
    }
}
  • @Command 注解, container 初始化的時候會有 scan 注解, 就能把這個類解析為 command 來使用
  • execute() 是 command 實際執(zhí)行的方法, \Symfony\Component\Console\Command\Command 作為基類采用這個方法, 而 \Hyperf\Command\Command 作為基類, 則是使用 handle() 方法
  • $serverFactory = $this->container->get(ServerFactory::class): container 的經典使用場之一, 由 container 來解決類的初始化, 使用放直接使用即可

ServerFactory 細節(jié)

還是上面的代碼:

$serverFactory = $this->container->get(ServerFactory::class)
  ->setEventDispatcher($this->container->get(EventDispatcherInterface::class))
  ->setLogger($this->container->get(StdoutLoggerInterface::class));

$serverConfig = $this->container->get(ConfigInterface::class)->get('server', []);
if (! $serverConfig) {
    throw new \InvalidArgumentException('At least one server should be defined.');
}

$serverFactory->configure($serverConfig);

$serverFactory->start();
  • 實例化 ServerFactory 時, 配置好框架的基礎組件 Event(事件模塊) / Logger(日志模塊)
  • 從框架通的 Config(配置) 組件獲取 server 配置, 即 config/autoload/server.php 文件的配置內容
  • server start, 配置好了 swoole server 后, 使用 Swoole\Server->start() 啟動服務即可

server config 的實現(xiàn)細節(jié)

server config 的實現(xiàn)細節(jié), 直接跟讀代碼定位到:

// \Hyperf\Server\Server::initServers
    protected function initServers(ServerConfig $config)
    {
        $servers = $this->sortServers($config->getServers());

        foreach ($servers as $server) {
            $name = $server->getName();
            $type = $server->getType();
            $host = $server->getHost();
            $port = $server->getPort();
            $sockType = $server->getSockType();
            $callbacks = $server->getCallbacks();
            ...
  • 先根據(jù) swoole 的限制, 如果配置了多個 server, 需要先啟動 http/ws server, 再通過 addPort() 的方式添加其余的 server, 這一步 hyperf 框架已經處理掉了
  • 綁定 swoole server 需要 callback(回調函數(shù))
  • 觸發(fā) BeforeMainServerStart / BeforeServerStart 等事件

深入 server start

等等, server start 這么簡單 ?! 再來回顧一下 php bin/hyperf.php start:

root@820d21e61cd8 /d/hyperf-demo# php bin/hyperf.php start
Scanning ...
Scan completed.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Di\Listener\BootApplicationListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\RpcClient\Listener\AddConsumerDefinitionListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Paginator\Listener\PageResolverListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\JsonRpc\Listener\RegisterProtocolListener listener.
[DEBUG] Event Hyperf\Framework\Event\BeforeMainServerStart handled by Hyperf\Amqp\Listener\BeforeMainServerStartListener listener.
[DEBUG] Event Hyperf\Framework\Event\BeforeMainServerStart handled by Hyperf\Process\Listener\BootProcessListener listener.
[DEBUG] Event Hyperf\Framework\Event\OnStart handled by Hyperf\Server\Listener\InitProcessTitleListener listener.
[DEBUG] Event Hyperf\Framework\Event\OnManagerStart handled by Hyperf\Server\Listener\InitProcessTitleListener listener.
[INFO] Worker#1 started.
[INFO] TaskWorker#2 started.
[DEBUG] Event Hyperf\Framework\Event\AfterWorkerStart handled by Hyperf\Server\Listener\InitProcessTitleListener listener.
[DEBUG] Event Hyperf\Framework\Event\AfterWorkerStart handled by Hyperf\Server\Listener\AfterWorkerStartListener listener.
[DEBUG] Event Hyperf\Process\Event\BeforeProcessHandle handled by Hyperf\Server\Listener\InitProcessTitleListener listener.
[DEBUG] Event Hyperf\Process\Event\BeforeProcessHandle handled by Hyperf\Server\Listener\InitProcessTitleListener listener.
[DEBUG] Event Hyperf\Framework\Event\MainWorkerStart handled by Hyperf\Amqp\Listener\MainWorkerStartListener listener.
[DEBUG] Event Hyperf\Framework\Event\AfterWorkerStart handled by Hyperf\Server\Listener\InitProcessTitleListener listener.
[DEBUG] Event Hyperf\Framework\Event\AfterWorkerStart handled by Hyperf\Server\Listener\AfterWorkerStartListener listener.
[INFO] Process[queue.default.0] start.
[DEBUG] Event Hyperf\Process\Event\BeforeProcessHandle handled by Hyperf\Process\Listener\LogBeforeProcessStartListener listener.
[INFO] Worker#0 started.
[INFO] Process[TestConsumer-hyperf.1] start.
[DEBUG] Event Hyperf\Process\Event\BeforeProcessHandle handled by Hyperf\Process\Listener\LogBeforeProcessStartListener listener.
[DEBUG] Event Hyperf\Framework\Event\AfterWorkerStart handled by Hyperf\Server\Listener\InitProcessTitleListener listener.
[INFO] HTTP Server listening at 0.0.0.0:9501
[DEBUG] Event Hyperf\Framework\Event\AfterWorkerStart handled by Hyperf\Server\Listener\AfterWorkerStartListener listener.
[INFO] TaskWorker#3 started.
[DEBUG] Event Hyperf\Framework\Event\AfterWorkerStart handled by Hyperf\Server\Listener\InitProcessTitleListener listener.
[DEBUG] Event Hyperf\Framework\Event\AfterWorkerStart handled by Hyperf\Server\Listener\AfterWorkerStartListener listener.
[DEBUG] Event Hyperf\Process\Event\BeforeProcessHandle handled by Hyperf\Server\Listener\InitProcessTitleListener listener.
[INFO] Process[TestConsumer-hyperf.0] start.
[DEBUG] Event Hyperf\Process\Event\BeforeProcessHandle handled by Hyperf\Process\Listener\LogBeforeProcessStartListener listener.

是的, 使用了 Event 機制帶來的靈活性, swoole Process 就是這個過程中啟動的, 而 hyperf 中很多組件底層都是使用的 swoole Process 實現(xiàn)的, 這里只給出調用鏈路, 感興趣的小伙伴自己去瞧哦:

// 觸發(fā) BeforeMainServerStart 事件
// vendor/hyperf/server/src/Server.php:110
$this->eventDispatcher->dispatch(new BeforeMainServerStart($this->server, $config->toArray()));

// 事件監(jiān)聽器處理
\Hyperf\Process\Listener\BootProcessListener::process

// 啟動 swoole process
\Hyperf\Process\AbstractProcess::bind

// 對應的 swoole 方法
\Swoole\Server::addProcess

寫在最后

start 命令對源碼閱讀確實是一個相當有挑戰(zhàn)的部分:

  • 對 swoole 方法的封裝, 要發(fā)揮出 swoole 超強能力, 所以說 swoole 的基礎知識很重要
  • hyperf 多個基礎組件的聯(lián)動, 包括 container / event / log / config

希望看到這里, 你可以感受到 hyperf 和 swoole 的強大之處, 頭腦中大概能對 hyperf 運行的 生命周期 有個大致的了解

下篇我們開始協(xié)程的話題, 以及轉到協(xié)程下編程必備的組件, 協(xié)程編程須知等內容.

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容