Files
kiri-rpc/src/JsonRpcPoolTransporter.php
T

69 lines
1.3 KiB
PHP
Raw Normal View History

2021-10-28 18:24:46 +08:00
<?php
namespace Kiri\Rpc;
2021-11-30 15:10:01 +08:00
use Note\Inject;
2021-10-28 18:24:46 +08:00
use Exception;
use Http\Message\Response;
use Http\Message\Stream;
use Kiri\Abstracts\Config;
use Kiri\Exception\ConfigException;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Swoole\Coroutine\Client;
class JsonRpcPoolTransporter implements ClientInterface
{
use TraitTransporter;
2021-10-28 18:52:38 +08:00
#[Inject(ClientPool::class)]
2021-10-28 18:24:46 +08:00
public ClientPool $pool;
const POOL_NAME = 'rpc.client.pool';
/**
*/
public function init()
{
}
/**
* @param RequestInterface $request
* @return ResponseInterface
* @throws Exception
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
$content = $request->getBody()->getContents();
2021-10-28 18:31:25 +08:00
2021-10-28 18:34:21 +08:00
$response = $this->request($client = $this->getClient(), $content, false);
2021-10-28 18:31:25 +08:00
2021-10-28 18:46:14 +08:00
$this->pool->push($client, $this->config['ServiceAddress'], $this->config['ServicePort']);
2021-10-28 18:31:25 +08:00
return (new Response())->withBody(new Stream($response));
2021-10-28 18:24:46 +08:00
}
/**
* @return Client|\Swoole\Client
* @throws ConfigException
* @throws Exception
*/
private function getClient(): Client|\Swoole\Client
{
2021-10-28 18:52:38 +08:00
$this->config['pool'] = Config::get('rpc.pool', ['max' => 10, 'min' => 1, 'waite' => 60]);
return $this->pool->get($this->config, function () {
2021-10-28 18:24:46 +08:00
return $this->newClient();
});
}
}