diff --git a/ClientPool.php b/ClientPool.php index c30acb0..e3a796c 100644 --- a/ClientPool.php +++ b/ClientPool.php @@ -3,12 +3,14 @@ namespace Kiri\Rpc; use Exception; -use Kiri\Abstracts\Component; -use Kiri\Context; -use Kiri\Exception\ConfigException; use Kiri; +use Kiri\Abstracts\Component; +use Kiri\Annotation\Inject; +use Kiri\Events\EventProvider; +use Kiri\Exception\ConfigException; use Kiri\Pool\Alias; use Kiri\Pool\Pool; +use Kiri\Server\Events\OnBeforeShutdown; use Swoole\Client; @@ -32,6 +34,31 @@ class ClientPool extends Component public int $waite; + #[Inject(EventProvider::class)] + public EventProvider $provider; + + + private array $names = []; + + + public function init() + { + $this->provider->on(OnBeforeShutdown::class, [$this, 'onBeforeShutdown']); + } + + + /** + * @return void + * @throws Exception + */ + public function onBeforeShutdown() + { + foreach ($this->names as $name) { + $this->getPool()->clean($name); + } + } + + /** * @param $config * @param callable $callback @@ -45,6 +72,8 @@ class ClientPool extends Component $pool = $config['pool'] ?? ['min' => 1, 'max' => 100]; + $this->names[] = $coroutineName; + return $this->getPool()->get($coroutineName, $callback, $pool['min'] ?? 1); } diff --git a/JsonRpcPoolTransporter.php b/JsonRpcPoolTransporter.php index 0428f22..3b0b63a 100644 --- a/JsonRpcPoolTransporter.php +++ b/JsonRpcPoolTransporter.php @@ -44,7 +44,7 @@ class JsonRpcPoolTransporter implements RpcClientInterface $client = $this->getClient(); - $response = $this->request($client, $content, false); + $response = $this->request($client, $content); $this->pool->push($client, $this->config['Address'], $this->config['Port']); diff --git a/JsonRpcTransporter.php b/JsonRpcTransporter.php index 3718163..1e8c032 100644 --- a/JsonRpcTransporter.php +++ b/JsonRpcTransporter.php @@ -28,9 +28,11 @@ class JsonRpcTransporter implements RpcClientInterface { $content = $request->getBody()->getContents(); - $response = $this->request($this->newClient(), $content, true); + $body = $this->request($this->newClient(), $content); - return (new Response())->withBody(new Stream($response)); + $response = \Kiri::getDi()->get(ResponseInterface::class); + + return $response->withBody(new Stream($body)); } diff --git a/TraitTransporter.php b/TraitTransporter.php index d36885e..34e8b11 100644 --- a/TraitTransporter.php +++ b/TraitTransporter.php @@ -32,17 +32,12 @@ trait TraitTransporter /** * @param Client|Coroutine\Client $client * @param $content - * @param bool $isClose * @return mixed */ - private function request(Client|Coroutine\Client $client, $content, bool $isClose): mixed + private function request(Client|Coroutine\Client $client, $content): mixed { $client->send($content); - $read = $client->recv(); - if ($isClose) { - $client->close(); - } - return $read; + return $client->recv(); }