Files
kiri-rpc/ClientPool.php
T

115 lines
2.4 KiB
PHP
Raw Permalink Normal View History

2022-01-09 14:00:32 +08:00
<?php
namespace Kiri\Rpc;
use Exception;
2022-06-08 17:19:32 +08:00
use Kiri;
2022-01-09 14:00:32 +08:00
use Kiri\Abstracts\Component;
use Kiri\Pool\Pool;
2022-06-08 17:19:32 +08:00
use Kiri\Server\Events\OnBeforeShutdown;
2023-05-20 23:05:38 +08:00
use ReflectionException;
2023-10-24 17:22:31 +08:00
use Swoole\Coroutine\Client as CoroutineClient;
use Swoole\Client as AsyncClient;
2022-01-09 14:00:32 +08:00
/**
*
*/
class ClientPool extends Component
{
2023-05-20 23:05:38 +08:00
public int $max;
public int $min;
private array $names = [];
2023-10-24 17:22:31 +08:00
/**
* @return void
*/
2023-05-20 23:05:38 +08:00
public function init(): void
{
on(OnBeforeShutdown::class, [$this, 'onBeforeShutdown']);
}
/**
* @return void
* @throws Exception
*/
public function onBeforeShutdown(): void
{
$pool = Kiri::getDi()->get(Pool::class);
foreach ($this->names as $name) {
$pool->clean($name);
}
}
/**
* @param $config
* @return resource
2023-10-24 17:22:31 +08:00
* @throws Exception
2023-05-20 23:05:38 +08:00
*/
public function get($config): mixed
{
$coroutineName = $config['Address'] . '::' . $config['Port'];
if (!in_array($coroutineName, $this->names)) {
$this->names[] = $coroutineName;
}
return $this->getPool($config['Address'], $config['Port'])->get($coroutineName);
}
/**
2023-10-24 17:22:31 +08:00
* @param CoroutineClient|AsyncClient $client
2023-05-20 23:05:38 +08:00
* @param $host
* @param $port
2023-10-24 17:22:31 +08:00
* @throws Exception
2023-05-20 23:05:38 +08:00
*/
2023-10-24 17:22:31 +08:00
public function push(CoroutineClient|AsyncClient $client, $host, $port)
2023-05-20 23:05:38 +08:00
{
$this->getPool($host, $port)->push($host . '::' . $port, $client);
}
/**
2023-10-24 17:22:31 +08:00
* @param string $host
* @param int $port
2023-05-20 23:05:38 +08:00
* @return Pool
* @throws ReflectionException
*/
2023-10-24 17:22:31 +08:00
public function getPool(string $host, int $port): Pool
2023-05-20 23:05:38 +08:00
{
$pool = Kiri::getDi()->get(Pool::class);
2023-10-24 17:22:31 +08:00
$pool->created($host . '::' . $port, 10, [$this, 'connect']);
2023-05-20 23:05:38 +08:00
return $pool;
}
2022-01-09 14:00:32 +08:00
2023-10-24 17:22:31 +08:00
/**
* @param $host
* @param $port
* @return CoroutineClient|AsyncClient
* @throws Exception
*/
public function connect($host, $port): CoroutineClient|AsyncClient
{
if (Kiri\Di\Context::inCoroutine()) {
$client = new CoroutineClient(SWOOLE_SOCK_TCP);
} else {
$client = new AsyncClient(SWOOLE_SOCK_TCP);
}
if (!$client->connect($host, $port, 3)) {
throw new Exception('Connect ' . $host . '::' . $port . ' fail');
}
return $client;
}
2022-01-09 14:00:32 +08:00
}