Files
kiri-rpc/TraitTransporter.php
T

102 lines
2.1 KiB
PHP
Raw Normal View History

2022-01-09 14:00:32 +08:00
<?php
namespace Kiri\Rpc;
use Exception;
2022-09-23 18:55:46 +08:00
use JetBrains\PhpStorm\ArrayShape;
use Kiri\Annotation\Inject;
2022-01-09 14:00:32 +08:00
use Kiri\Context;
2022-05-04 03:22:31 +08:00
use Kiri\Core\Json;
2022-01-09 14:00:32 +08:00
use Swoole\Client;
use Swoole\Coroutine;
trait TraitTransporter
{
2022-09-23 18:55:46 +08:00
/**
* @var RpcManager
*/
#[Inject(RpcManager::class)]
public RpcManager $manager;
2022-01-09 14:00:32 +08:00
protected array $config;
2022-09-23 18:55:46 +08:00
/**
* @param Client|Coroutine\Client $client
* @param $content
* @return string|bool
*/
private function request(Client|Coroutine\Client $client, $content): string|bool
{
$client->send($content);
return $client->recv();
}
2022-01-09 14:00:32 +08:00
/**
2022-09-23 18:55:46 +08:00
* @param string $service
2022-01-09 14:00:32 +08:00
* @return $this
2022-09-23 18:55:46 +08:00
* @throws RpcServiceException
2022-01-09 14:00:32 +08:00
*/
2022-09-23 18:55:46 +08:00
private function get_consul(string $service): static
2022-01-09 14:00:32 +08:00
{
2022-09-23 18:55:46 +08:00
if (empty($service)) {
throw new RpcServiceException('You need set rpc service name if used.');
}
$sf = $this->manager->getServices($service);
if (empty($sf) || !is_array($sf)) {
throw new RpcServiceException('You need set rpc service name if used.');
}
$this->config = $this->_loadRand($sf);
2022-01-09 14:00:32 +08:00
return $this;
}
/**
2022-09-23 18:55:46 +08:00
* @param $services
* @return array
2022-01-09 14:00:32 +08:00
*/
2022-09-23 18:55:46 +08:00
#[ArrayShape(['Address' => "mixed", 'Port' => "mixed"])]
private function _loadRand($services): array
2022-01-09 14:00:32 +08:00
{
2022-09-23 18:55:46 +08:00
$array = [];
foreach ($services as $value) {
$value['Weight'] = $value['Weights']['Passing'];
$array[] = $value;
}
if (count($array) < 2) {
$luck = $array[0];
} else {
$luck = Luckdraw::luck($array, 'Weight');
}
return [
'Address' => $luck['TaggedAddresses']['wan_ipv4']['Address'],
'Port' => $luck['TaggedAddresses']['wan_ipv4']['Port']
];
2022-01-09 14:00:32 +08:00
}
2022-09-23 18:55:46 +08:00
2022-01-09 14:00:32 +08:00
/**
* @return Client|Coroutine\Client
* @throws Exception
*/
private function newClient(): Coroutine\Client|Client
{
2022-05-04 03:53:37 +08:00
if (Context::inCoroutine()) {
$client = new Coroutine\Client(SWOOLE_SOCK_TCP);
} else {
$client = new Client(SWOOLE_SOCK_TCP);
}
2022-01-09 14:00:32 +08:00
[$host, $port] = [$this->config['Address'], $this->config['Port']];
if (!$client->isConnected() && !$client->connect($host, $port, 60)) {
throw new Exception('connect fail.');
}
return $client;
}
}