Files
kiri-core/Rpc/Client.php
T

95 lines
1.9 KiB
PHP
Raw Normal View History

2021-03-23 02:29:48 +08:00
<?php
namespace Rpc;
2021-03-23 10:30:14 +08:00
use Exception;
2021-03-23 02:29:48 +08:00
use Snowflake\Abstracts\Component;
use Snowflake\Abstracts\Config;
use Snowflake\Exception\ConfigException;
use Swoole\Coroutine\Client as CClient;
/**
* Class Client
* @package Rpc
*/
class Client extends Component
{
2021-03-23 16:42:57 +08:00
public array $config = [];
2021-03-23 02:29:48 +08:00
2021-03-23 16:42:57 +08:00
public string $service = '';
2021-03-23 02:29:48 +08:00
2021-03-23 16:50:59 +08:00
private ?CClient $client = null;
2021-03-23 02:29:48 +08:00
2021-03-23 16:14:05 +08:00
/**
* @param string $cmd
2021-03-23 10:30:14 +08:00
* @param array $param
* @return mixed
* @throws Exception
*/
2021-03-23 16:14:05 +08:00
public function dispatch(string $cmd, array $param): mixed
{
2021-03-23 16:50:59 +08:00
if (empty($this->config)) {
2021-03-23 16:56:05 +08:00
return $this->addError('Related service not found(404)');
2021-03-23 16:14:05 +08:00
}
if (!($this->client instanceof CClient)) {
$this->client = $this->getClient();
}
if (!$this->client->isConnected()) {
2021-03-23 16:56:05 +08:00
$settings = [$this->config['host'], $this->config['port'], $this->config['timeout'] ?? 1];
if (!$this->client->connect(...$settings)) {
return $this->addError($this->client->errMsg . '(' . $this->client->errCode . ')');
2021-03-23 16:14:05 +08:00
}
}
$isSend = $this->client->send(serialize(['cmd' => $cmd, 'body' => $param]));
if ($isSend === false) {
2021-03-23 16:56:05 +08:00
return $this->addError($this->client->errMsg . '(' . $this->client->errCode . ')');
2021-03-23 16:14:05 +08:00
}
2021-03-23 16:56:53 +08:00
if (is_bool($unpack = unserialize($this->client->recv()))) {
return $this->addError('Service return data format error(500)');
}
return $unpack;
2021-03-23 16:14:05 +08:00
}
2021-03-23 16:52:45 +08:00
/**
* 断开链接
*/
public function close()
{
if (!$this->client || !$this->client->isConnected()) {
return;
}
$this->client->close();
}
2021-03-23 16:14:05 +08:00
/**
* @return mixed
* @throws Exception
*/
public function getClient(): CClient
{
return objectPool(CClient::class, function () {
2021-03-23 16:48:10 +08:00
$client = new CClient($this->config['mode'] ?? SWOOLE_SOCK_TCP);
2021-03-23 16:14:05 +08:00
$client->set([
'timeout' => 0.5,
'connect_timeout' => 1.0,
'write_timeout' => 10.0,
'read_timeout' => 0.5,
'open_tcp_keepalive' => true,
]);
2021-03-23 16:48:10 +08:00
return $client;
2021-03-23 16:14:05 +08:00
});
}
2021-03-23 02:29:48 +08:00
}