Files
kiri-rpc/src/Annotation/JsonRpc.php
T

75 lines
1.8 KiB
PHP
Raw Normal View History

2021-10-26 18:58:09 +08:00
<?php
namespace Kiri\Rpc\Annotation;
2021-10-28 10:52:09 +08:00
use Annotation\Attribute;
2021-10-29 18:06:04 +08:00
use Kiri\Abstracts\Config;
use Kiri\Consul\Agent;
use Kiri\Exception\ConfigException;
use Kiri\Kiri;
2021-10-28 15:14:21 +08:00
use Kiri\Rpc\RpcManager;
use ReflectionException;
2021-10-28 10:52:09 +08:00
#[\Attribute(\Attribute::TARGET_CLASS)] class JsonRpc extends Attribute
2021-10-26 18:58:09 +08:00
{
/**
2021-11-01 18:18:39 +08:00
* @param string $service
2021-10-29 18:06:04 +08:00
* @param string $driver
* @param array $checkOptions
2021-10-26 18:58:09 +08:00
*/
2021-11-01 18:18:39 +08:00
public function __construct(public string $service, public string $driver, public array $checkOptions = [
2021-10-29 18:06:04 +08:00
"DeregisterCriticalServiceAfter" => "1m",
"Http" => "http://127.0.0.1:9527",
"Interval" => "1s",
"Timeout" => "1s"
])
2021-10-26 18:58:09 +08:00
{
}
2021-10-28 10:52:09 +08:00
/**
* @param mixed $class
* @param mixed|string $method
* @return mixed
2021-10-28 15:14:21 +08:00
* @throws ReflectionException
2021-10-29 18:06:04 +08:00
* @throws ConfigException
2021-10-28 10:52:09 +08:00
*/
2021-10-28 15:14:21 +08:00
public function execute(mixed $class, mixed $method = ''): bool
2021-10-28 10:52:09 +08:00
{
2021-11-05 01:18:49 +08:00
$default = $this->create();
$agent = Kiri::getDi()->get(Agent::class);
$data = $agent->service->register($default);
if ($data->getStatusCode() != 200) {
exit($data->getBody()->getContents());
}
return RpcManager::add($this->service, $class, $default['id']);
2021-10-29 18:06:04 +08:00
}
/**
* @throws ConfigException
*/
protected function create(): array
{
2021-10-29 18:28:39 +08:00
$content = current(swoole_get_local_ip());
2021-10-29 18:06:04 +08:00
return [
2021-11-01 18:18:39 +08:00
"id" => "rpc.json.{$this->service}." . md5(__DIR__ . '.' . md5($content)),
"name" => $this->service,
2021-10-29 18:28:39 +08:00
"address" => $content,
2021-10-29 18:06:04 +08:00
"port" => 9526,
"enableTagOverride" => true,
"check" => [
"DeregisterCriticalServiceAfter" => "1m",
"TCP" => $content . ":" . Config::get('rpc.port'),
"Interval" => "1s",
"Timeout" => "1s"
]
];
2021-10-28 10:52:09 +08:00
}
2021-10-26 18:58:09 +08:00
}