如何让 Hyperf 只启动一个服务 #3091
Answered
by
limingxinleo
limingxinleo
asked this question in
Q&A
-
众所周知 Hyperf 是不支持单独启动某个服务的,所以要如何实现这个功能呢? |
Beta Was this translation helpful? Give feedback.
Answered by
limingxinleo
Jan 8, 2021
Replies: 1 comment 2 replies
-
以下我们提供一种极为友好的方式,处理这个问题。 如何扩展先让我们阅读一下
可以看到,我们在执行具体的 编写 Listener我们从 接下来我们只需要根据对应的 代码如下 <?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Listener;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Input\InputOption;
/**
* @Listener
*/
class ConsoleCommandEventListener implements ListenerInterface
{
/**
* @var ContainerInterface
*/
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function listen(): array
{
return [
ConsoleCommandEvent::class,
];
}
/**
* @param ConsoleCommandEvent $event
*/
public function process(object $event)
{
if ($event instanceof ConsoleCommandEvent) {
$command = $event->getCommand();
$command->addOption('server', 'S', InputOption::VALUE_OPTIONAL, '需要启动的服务');
$input = $event->getInput();
$input->bind($command->getDefinition());
if ($input->getOption('server') != null) {
$config = $this->container->get(ConfigInterface::class);
$servers = $config->get('server.servers', []);
$result = [];
foreach ($servers as $server) {
if ($input->getOption('server') == $server['name']) {
$result[] = $server;
}
}
if (empty($result)) {
throw new BusinessException(ErrorCode::SERVER_ERROR, '服务名不存在');
}
$config->set('server.servers', $result);
}
}
}
} 测试结果如下,可见符合我们的预期
|
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
limingxinleo
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
以下我们提供一种极为友好的方式,处理这个问题。
DEMO
如何扩展
先让我们阅读一下
Symfony\Component\Console\Application
中的一段代码