Skip to content

如何区别本地和线上环境,针对不同环境发布服务到 Consul #3023

Answered by limingxinleo
limingxinleo asked this question in Q&A
Discussion options

You must be logged in to vote

以下代码片段,全部省略不想干的部分

原因

让我们修改源码 Hyperf\ServiceGovernance\Listener\RegisterServiceListener

public function process(object $event)
{
    $this->registeredServices = [];
    $continue = true;
    while ($continue) {
        dump(__METHOD__);
    }
}

启动服务后,我们便可以看到

$ php bin/hyperf.php start
"Hyperf\ServiceGovernance\Listener\RegisterServiceListener::process"
[INFO] HTTP Server listening at 0.0.0.0:9501

源码中我们可以清楚的看到,监听器会监听 MainWorkerStartMainCoroutineServerStart 事件

然后执行 process() 方法,故会执行发布服务到注册中心的逻辑

那我们的解决办法,就是可以拦截这里,达到我们的效果。

解决方案

使用 AOP

无侵入修改代码,我们立刻会想到使用 AOP 来实现,让我们编写一个 RegisterServiceAspect

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hy…

Replies: 2 comments 4 replies

Comment options

You must be logged in to vote
4 replies
@limingxinleo
Comment options

@caiking
Comment options

@limingxinleo
Comment options

@caiking
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by limingxinleo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants