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 执行的命令, 是基于 Symfony\Component\Console\Application 提供的命令行应用提供的功能, 初始内置的 command, 是有 ConfigProvider 配置项中的 command 字段设置的. 那么, 我们将要执行的 start 命令, 是由哪个 command 提供的呢?

可以根据 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 实际执行的方法, \Symfony\Component\Console\Command\Command 作为基类采用这个方法, 而 \Hyperf\Command\Command 作为基类, 则是使用 handle() 方法
  • $serverFactory = $this->container->get(ServerFactory::class): container 的经典使用场之一, 由 container 来解决类的初始化, 使用放直接使用即可

ServerFactory 细节

还是上面的代码:

$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 的实现细节

server config 的实现细节, 直接跟读代码定位到:

// \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();
            ...
  • 先根据 swoole 的限制, 如果配置了多个 server, 需要先启动 http/ws server, 再通过 addPort() 的方式添加其余的 server, 这一步 hyperf 框架已经处理掉了
  • 绑定 swoole server 需要 callback(回调函数)
  • 触发 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 实现的, 这里只给出调用链路, 感兴趣的小伙伴自己去瞧哦:

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

// 事件监听器处理
\Hyperf\Process\Listener\BootProcessListener::process

// 启动 swoole process
\Hyperf\Process\AbstractProcess::bind

// 对应的 swoole 方法
\Swoole\Server::addProcess

写在最后

start 命令对源码阅读确实是一个相当有挑战的部分:

  • 对 swoole 方法的封装, 要发挥出 swoole 超强能力, 所以说 swoole 的基础知识很重要
  • hyperf 多个基础组件的联动, 包括 container / event / log / config

希望看到这里, 你可以感受到 hyperf 和 swoole 的强大之处, 头脑中大概能对 hyperf 运行的 生命周期 有个大致的了解

下篇我们开始协程的话题, 以及转到协程下编程必备的组件, 协程编程须知等内容.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容