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, 來(lái)會(huì)一會(huì)強(qiáng)大到爆炸的 swoole

開(kāi)始之前, 請(qǐng)確保自己具備一定的 swoole 基礎(chǔ)知識(shí), 這篇適合你:

千萬(wàn)不要小看了 基礎(chǔ)知識(shí), 與其一直卡殼浪費(fèi)時(shí)間, 不如沉下心來(lái)好好讀一下 swoole wiki, 看似 艱辛, 絕對(duì)比沒(méi)有這些基礎(chǔ)知識(shí)導(dǎo)致的時(shí)間浪費(fèi)要?jiǎng)澦愕枚嗟枚嗟枚?!

Command 基礎(chǔ)

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

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

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

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

對(duì)應(yīng)的 start 命令, 就可以通過(guò)全局搜索 parent::__construct('start') 查詢到

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

OK, 就定位到了我們 start 命令對(duì)應(yīng)的代碼: \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 初始化的時(shí)候會(huì)有 scan 注解, 就能把這個(gè)類解析為 command 來(lái)使用
  • execute() 是 command 實(shí)際執(zhí)行的方法, \Symfony\Component\Console\Command\Command 作為基類采用這個(gè)方法, 而 \Hyperf\Command\Command 作為基類, 則是使用 handle() 方法
  • $serverFactory = $this->container->get(ServerFactory::class): container 的經(jīng)典使用場(chǎng)之一, 由 container 來(lái)解決類的初始化, 使用放直接使用即可

ServerFactory 細(xì)節(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();
  • 實(shí)例化 ServerFactory 時(shí), 配置好框架的基礎(chǔ)組件 Event(事件模塊) / Logger(日志模塊)
  • 從框架通的 Config(配置) 組件獲取 server 配置, 即 config/autoload/server.php 文件的配置內(nèi)容
  • server start, 配置好了 swoole server 后, 使用 Swoole\Server->start() 啟動(dòng)服務(wù)即可

server config 的實(shí)現(xiàn)細(xì)節(jié)

server config 的實(shí)現(xiàn)細(xì)節(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 的限制, 如果配置了多個(gè) server, 需要先啟動(dòng) http/ws server, 再通過(guò) addPort() 的方式添加其余的 server, 這一步 hyperf 框架已經(jīng)處理掉了
  • 綁定 swoole server 需要 callback(回調(diào)函數(shù))
  • 觸發(fā) BeforeMainServerStart / BeforeServerStart 等事件

深入 server start

等等, server start 這么簡(jiǎn)單 ?! 再來(lái)回顧一下 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 機(jī)制帶來(lái)的靈活性, swoole Process 就是這個(gè)過(guò)程中啟動(dòng)的, 而 hyperf 中很多組件底層都是使用的 swoole Process 實(shí)現(xiàn)的, 這里只給出調(diào)用鏈路, 感興趣的小伙伴自己去瞧哦:

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

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

// 啟動(dòng) swoole process
\Hyperf\Process\AbstractProcess::bind

// 對(duì)應(yīng)的 swoole 方法
\Swoole\Server::addProcess

寫(xiě)在最后

start 命令對(duì)源碼閱讀確實(shí)是一個(gè)相當(dāng)有挑戰(zhàn)的部分:

  • 對(duì) swoole 方法的封裝, 要發(fā)揮出 swoole 超強(qiáng)能力, 所以說(shuō) swoole 的基礎(chǔ)知識(shí)很重要
  • hyperf 多個(gè)基礎(chǔ)組件的聯(lián)動(dòng), 包括 container / event / log / config

希望看到這里, 你可以感受到 hyperf 和 swoole 的強(qiáng)大之處, 頭腦中大概能對(duì) hyperf 運(yùn)行的 生命周期 有個(gè)大致的了解

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

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

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容