Files
kiri-rpc/RpcManager.php
T

77 lines
1.4 KiB
PHP
Raw Normal View History

2022-01-09 14:00:32 +08:00
<?php
namespace Kiri\Rpc;
2022-01-13 18:25:29 +08:00
use Exception;
use Kiri;
2022-05-31 10:53:33 +08:00
use Kiri\Abstracts\Config;
2022-01-09 14:00:32 +08:00
use Kiri\Abstracts\Component;
2022-03-02 15:15:36 +08:00
use Kiri\Annotation\Inject;
2022-01-09 14:00:32 +08:00
use Kiri\Consul\Agent;
use Kiri\Consul\Health;
2022-03-02 16:27:15 +08:00
use Kiri\Message\Handler\Router;
2022-01-09 14:00:32 +08:00
2022-06-16 17:38:23 +08:00
/**
* class RpcManager
*/
2022-01-09 14:00:32 +08:00
class RpcManager extends Component
{
2022-06-16 17:38:23 +08:00
2022-01-09 14:00:32 +08:00
/**
2022-06-16 17:38:23 +08:00
* @var Health
2022-01-09 14:00:32 +08:00
*/
2022-03-02 15:15:36 +08:00
#[Inject(Health::class)]
public Health $health;
2022-06-16 17:38:23 +08:00
2022-01-09 14:00:32 +08:00
/**
* @param $serviceName
2022-03-02 15:15:36 +08:00
* @return array|null
2022-01-09 14:00:32 +08:00
*/
2022-03-02 15:15:36 +08:00
public function getServices($serviceName): ?array
2022-01-09 14:00:32 +08:00
{
2022-03-02 15:15:36 +08:00
$lists = $this->health->setQuery('passing=true')->service($serviceName);
if ($lists->getStatusCode() != 200) {
return null;
2022-01-09 14:00:32 +08:00
}
2022-03-02 15:15:36 +08:00
$body = json_decode($lists->getBody(), true);
if (empty($body)) {
return null;
2022-01-09 14:00:32 +08:00
}
2022-03-02 15:15:36 +08:00
return array_column($body, 'Service');
2022-01-09 14:00:32 +08:00
}
2022-06-16 17:38:23 +08:00
2022-01-09 14:00:32 +08:00
/**
* @param string $name
* @param string $class
* @return bool
*/
2022-05-31 11:11:12 +08:00
public function add(string $name, string $class): bool
2022-01-09 14:00:32 +08:00
{
2022-03-02 16:27:15 +08:00
Router::addServer('rpc', static function () use ($name, $class) {
Router::get($name, $class);
});
2022-01-09 14:00:32 +08:00
return true;
}
2022-06-16 17:38:23 +08:00
2022-01-09 14:00:32 +08:00
/**
2022-06-16 17:38:23 +08:00
* @param array $config
2022-05-31 10:53:33 +08:00
* @return void
2022-01-09 14:00:32 +08:00
*/
2022-06-16 17:38:23 +08:00
public function register(array $config): void
2022-01-09 14:00:32 +08:00
{
2022-01-11 14:41:06 +08:00
$agent = Kiri::getDi()->get(Agent::class);
2022-06-16 17:38:23 +08:00
$agent->checks->deregister($config['ID']);
$agent->service->deregister($config['ID']);
$data = $agent->service->register($config);
2022-05-31 10:53:33 +08:00
if ($data->getStatusCode() != 200) {
$this->logger->error($data->getBody());
2022-01-09 14:00:32 +08:00
}
2022-06-16 17:38:23 +08:00
2022-01-09 14:00:32 +08:00
}
2022-06-16 17:38:23 +08:00
2022-01-09 14:00:32 +08:00
}