变更
This commit is contained in:
+54
-26
@@ -3,6 +3,8 @@
|
||||
namespace Kiri\Rpc;
|
||||
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\ArrayShape;
|
||||
use Kiri\Annotation\Inject;
|
||||
use Kiri\Context;
|
||||
use Kiri\Core\Json;
|
||||
use Swoole\Client;
|
||||
@@ -12,35 +14,72 @@ trait TraitTransporter
|
||||
{
|
||||
|
||||
|
||||
protected array $config;
|
||||
|
||||
|
||||
protected array $clients = [];
|
||||
|
||||
|
||||
/**
|
||||
* @param $config
|
||||
* @return $this
|
||||
* @var RpcManager
|
||||
*/
|
||||
public function withConfig($config): static
|
||||
{
|
||||
$this->config = $config;
|
||||
return $this;
|
||||
}
|
||||
#[Inject(RpcManager::class)]
|
||||
public RpcManager $manager;
|
||||
|
||||
|
||||
protected array $config;
|
||||
|
||||
|
||||
/**
|
||||
* @param Client|Coroutine\Client $client
|
||||
* @param $content
|
||||
* @return mixed
|
||||
* @return string|bool
|
||||
*/
|
||||
private function request(Client|Coroutine\Client $client, $content): mixed
|
||||
private function request(Client|Coroutine\Client $client, $content): string|bool
|
||||
{
|
||||
$client->send($content);
|
||||
return $client->recv();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $service
|
||||
* @return $this
|
||||
* @throws RpcServiceException
|
||||
*/
|
||||
private function get_consul(string $service): static
|
||||
{
|
||||
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);
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $services
|
||||
* @return array
|
||||
*/
|
||||
#[ArrayShape(['Address' => "mixed", 'Port' => "mixed"])]
|
||||
private function _loadRand($services): array
|
||||
{
|
||||
$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']
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return Client|Coroutine\Client
|
||||
* @throws Exception
|
||||
@@ -59,15 +98,4 @@ trait TraitTransporter
|
||||
return $client;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $config
|
||||
* @return string
|
||||
*/
|
||||
private function alias(array $config): string
|
||||
{
|
||||
return $config['Address'] . '::' . $config['Port'];
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user