86 Commits

Author SHA1 Message Date
as2252258 8824f711bb Revert "改名"
This reverts commit fdf58326
2022-01-20 19:04:16 +08:00
as2252258 f2d97832b5 Revert "改名"
This reverts commit fdf58326
2022-01-19 17:27:47 +08:00
as2252258 855e57a651 Revert "改名"
This reverts commit fdf58326
2022-01-19 16:39:29 +08:00
as2252258 0b3310b82e Revert "改名"
This reverts commit fdf58326
2022-01-14 11:29:16 +08:00
as2252258 e8cf7f29f0 Revert "改名"
This reverts commit fdf58326
2022-01-13 19:02:07 +08:00
as2252258 62e3b001f0 Revert "改名"
This reverts commit fdf58326
2022-01-13 19:00:01 +08:00
as2252258 f655cebdf3 Revert "改名"
This reverts commit fdf58326
2022-01-13 18:58:40 +08:00
as2252258 ee492d97ad Revert "改名"
This reverts commit fdf58326
2022-01-13 18:57:53 +08:00
as2252258 a16d841d98 Revert "改名"
This reverts commit fdf58326
2022-01-13 18:56:41 +08:00
as2252258 f015662fd6 Revert "改名"
This reverts commit fdf58326
2022-01-13 18:52:42 +08:00
as2252258 021dcae59b Revert "改名"
This reverts commit fdf58326
2022-01-13 18:50:19 +08:00
as2252258 c6dc34c821 Revert "改名"
This reverts commit fdf58326
2022-01-13 18:47:34 +08:00
as2252258 88c3958aba Revert "改名"
This reverts commit fdf58326
2022-01-13 18:42:42 +08:00
as2252258 24ebfac360 Revert "改名"
This reverts commit fdf58326
2022-01-13 18:41:16 +08:00
as2252258 b3c200b443 Revert "改名"
This reverts commit fdf58326
2022-01-13 18:34:23 +08:00
as2252258 3e2b50bf60 Revert "改名"
This reverts commit fdf58326
2022-01-13 18:33:56 +08:00
as2252258 89c142930e Revert "改名"
This reverts commit fdf58326
2022-01-13 18:29:51 +08:00
as2252258 1515d9695c Revert "改名"
This reverts commit fdf58326
2022-01-13 18:28:22 +08:00
as2252258 f1f7b1081d Revert "改名"
This reverts commit fdf58326
2022-01-13 18:27:36 +08:00
as2252258 07533e29f9 Revert "改名"
This reverts commit fdf58326
2022-01-13 18:25:29 +08:00
as2252258 4d60a24fac Revert "改名"
This reverts commit fdf58326
2022-01-12 14:10:33 +08:00
as2252258 4dc6bc661a Revert "改名"
This reverts commit fdf58326
2022-01-11 17:56:16 +08:00
as2252258 0d7fd5e356 Revert "改名"
This reverts commit fdf58326
2022-01-11 14:53:41 +08:00
as2252258 da16b0685d Revert "改名"
This reverts commit fdf58326
2022-01-11 14:51:50 +08:00
as2252258 febbdea8c8 Revert "改名"
This reverts commit fdf58326
2022-01-11 14:44:02 +08:00
as2252258 a45c3d875c Revert "改名"
This reverts commit fdf58326
2022-01-11 14:42:04 +08:00
as2252258 64d01c0a80 Revert "改名"
This reverts commit fdf58326
2022-01-11 14:41:06 +08:00
as2252258 bf5fe594e4 Revert "改名"
This reverts commit fdf58326
2022-01-11 14:30:58 +08:00
as2252258 5cfe3c6d6d Revert "改名"
This reverts commit fdf58326
2022-01-11 14:30:05 +08:00
as2252258 773e3c0f57 Revert "改名"
This reverts commit fdf58326
2022-01-11 14:26:57 +08:00
as2252258 b1c91343ef Revert "改名"
This reverts commit fdf58326
2022-01-11 14:25:24 +08:00
as2252258 3f821ca9d0 Revert "改名"
This reverts commit fdf58326
2022-01-11 14:23:48 +08:00
as2252258 d296b3107e Revert "改名"
This reverts commit fdf58326
2022-01-11 14:15:51 +08:00
as2252258 f606c58204 Revert "改名"
This reverts commit fdf58326
2022-01-11 14:13:51 +08:00
as2252258 6c1d986814 Revert "改名"
This reverts commit fdf58326
2022-01-10 11:39:56 +08:00
as2252258 da056b09c7 1 2022-01-09 16:07:57 +08:00
as2252258 4eefe54be0 e 2022-01-09 14:00:32 +08:00
as2252258 b0ed7650c5 Revert "改名"
This reverts commit fdf58326
2022-01-08 18:49:07 +08:00
as2252258 3d89cbd4c6 Revert "改名"
This reverts commit fdf58326
2022-01-05 15:22:29 +08:00
as2252258 0f2d19f3c7 Revert "改名"
This reverts commit fdf58326
2022-01-05 15:21:48 +08:00
as2252258 9001dd041e Revert "改名"
This reverts commit fdf58326
2022-01-04 15:56:37 +08:00
as2252258 1bb26b4680 改名 2021-12-24 14:53:59 +08:00
as2252258 a6d825ef9b 改名 2021-12-24 14:16:07 +08:00
as2252258 6cc0334b9b 改名 2021-12-24 11:55:09 +08:00
as2252258 d6cb6e40a8 改名 2021-12-24 11:53:24 +08:00
as2252258 fb10622960 改名 2021-12-24 11:34:29 +08:00
as2252258 2a9c36babb 改名 2021-12-24 11:31:48 +08:00
as2252258 bc4e506ea8 改名 2021-12-23 18:22:26 +08:00
as2252258 59089462e7 改名 2021-12-08 11:32:32 +08:00
as2252258 845b8b36d1 改名 2021-12-06 17:10:45 +08:00
as2252258 07436f7035 改名 2021-12-06 17:08:03 +08:00
as2252258 4d93fcaff2 改名 2021-12-03 15:42:05 +08:00
as2252258 2e01b60e1e 改名 2021-12-03 15:09:05 +08:00
as2252258 8d2ce1d45c 改名 2021-12-03 15:07:21 +08:00
as2252258 8a3ed5aea5 改名 2021-12-03 14:56:13 +08:00
as2252258 d50b6e6ec7 改名 2021-12-03 14:46:38 +08:00
as2252258 8f3bea7738 改名 2021-12-02 16:22:44 +08:00
as2252258 eec4ad8a8b 改名 2021-12-02 16:18:10 +08:00
as2252258 18d2ce66e6 改名 2021-12-02 16:13:57 +08:00
as2252258 a66de3f016 改名 2021-12-02 15:57:36 +08:00
as2252258 6fcd26f80f 改名 2021-12-02 15:53:25 +08:00
as2252258 3538393620 改名 2021-12-02 15:52:49 +08:00
as2252258 9a6575b438 改名 2021-12-02 15:48:32 +08:00
as2252258 7293e24f9d 改名 2021-12-02 15:41:39 +08:00
as2252258 646f6b1258 改名 2021-12-02 15:41:16 +08:00
as2252258 1189ab7b0c 改名 2021-12-02 15:40:45 +08:00
as2252258 7c36c32c65 改名 2021-12-02 15:39:47 +08:00
as2252258 f2d60f6982 改名 2021-12-02 15:38:49 +08:00
as2252258 6d242d42b0 改名 2021-12-02 15:36:54 +08:00
as2252258 5991ea9d3f 改名 2021-12-02 15:33:57 +08:00
as2252258 9af46754e7 改名 2021-12-02 15:32:54 +08:00
as2252258 23206bc683 改名 2021-12-02 15:26:43 +08:00
as2252258 439e3c566e 改名 2021-12-02 15:25:41 +08:00
as2252258 14d395be5e 改名 2021-12-02 14:40:10 +08:00
as2252258 a8a202ad6b 改名 2021-12-02 14:38:07 +08:00
as2252258 a8d3d1472f 改名 2021-12-02 14:25:50 +08:00
as2252258 f374fad591 改名 2021-12-02 14:24:26 +08:00
as2252258 4e2c4633c1 改名 2021-12-02 14:22:23 +08:00
as2252258 31a086e338 改名 2021-12-02 14:21:32 +08:00
as2252258 87d0d28847 改名 2021-12-02 14:20:19 +08:00
as2252258 c41bdd9c8e 改名 2021-12-02 14:17:52 +08:00
as2252258 e6ae1acd14 改名 2021-12-02 14:14:32 +08:00
as2252258 d2ec972c69 改名 2021-12-02 14:13:44 +08:00
as2252258 ce3647b5b7 改名 2021-12-02 14:12:27 +08:00
as2252258 19c9b692d4 改名 2021-12-02 14:06:57 +08:00
as2252258 7fef63fa39 改名 2021-12-01 19:04:59 +08:00
22 changed files with 1519 additions and 1319 deletions
+37 -37
View File
@@ -1,37 +1,37 @@
# Created by .ignore support plugin (hsz.mobi)
### Yii template
assets/*
!assets/.gitignore
protected/runtime/*
!protected/runtime/.gitignore
protected/data/*.db
themes/classic/views/
### Example user template template
### Example user template
# IntelliJ project files
.idea
*.iml
out
gen
db/
async-queue/
composer.lock
*.log
commands/result
config/setting.php
tests/
vendor/
runtime/
*.xml
*.lock
oot
d
composer.lock
# Created by .ignore support plugin (hsz.mobi)
### Yii template
assets/*
!assets/.gitignore
protected/runtime/*
!protected/runtime/.gitignore
protected/data/*.db
themes/classic/views/
### Example user template template
### Example user template
# IntelliJ project files
.idea
*.iml
out
gen
db/
async-queue/
composer.lock
*.log
commands/result
config/setting.php
tests/
vendor/
runtime/
*.xml
*.lock
oot
d
composer.lock
+18 -18
View File
@@ -1,18 +1,18 @@
<?php
namespace PHPSTORM_META {
// Reflect
use Kiri\Di\Container;
use Psr\Container\ContainerInterface;
override(ContainerInterface::get(0), map('@'));
override(Container::get(0), map('@'));
override(Container::make(0), map('@'));
override(Container::create(0), map('@'));
// override(\Hyperf\Utils\Context::get(0), map('@'));
// override(\make(0), map('@'));
override(\di(0), map('@'));
override(\duplicate(0), map('@'));
}
<?php
namespace PHPSTORM_META {
// Reflect
use Kiri\Di\Container;
use Psr\Container\ContainerInterface;
override(ContainerInterface::get(0), map('@'));
override(Container::get(0), map('@'));
override(Container::make(0), map('@'));
override(Container::create(0), map('@'));
// override(\Hyperf\Utils\Context::get(0), map('@'));
// override(\make(0), map('@'));
override(\di(0), map('@'));
override(\duplicate(0), map('@'));
}
+91
View File
@@ -0,0 +1,91 @@
<?php
namespace Kiri\Rpc\Annotation;
use Kiri\Abstracts\Config;
use Kiri\Core\Network;
use Kiri\Exception\ConfigException;
use Kiri;
use Kiri\Rpc\RpcManager;
use Kiri\Annotation\Attribute;
use ReflectionException;
#[\Attribute(\Attribute::TARGET_CLASS)] class JsonRpc extends Attribute
{
private string $uniqueId = '';
/**
* @param string $service
* @param string $driver
* @param array $tags
* @param array $meta
* @param array $checkOptions
* @param string $checkUrl
*/
public function __construct(public string $service, public string $driver, public array $tags = [], public array $meta = [], public array $checkOptions = [], public string $checkUrl = '')
{
$this->uniqueId = preg_replace('/(\w{11})(\w{4})(\w{3})(\w{8})(\w{6})/', '$1-$2-$3-$4-$5', md5(__DIR__ . 'Annotation' . md5(Network::local())));
}
/**
* @param mixed $class
* @param mixed|string $method
* @return mixed
* @throws ReflectionException
* @throws ConfigException
*/
public function execute(mixed $class, mixed $method = ''): bool
{
return Kiri::getDi()->get(RpcManager::class)->add($this->service, $class, $this->create());
}
/**
* @throws ConfigException
*/
protected function create(): array
{
$rpcPort = Config::get('rpc.port');
if (empty($this->checkUrl)) {
$this->checkUrl = Network::local() . ":" . Config::get('rpc.port');
}
$defaultConfig = [
"ID" => "rpc.json.{$this->service}." . $this->uniqueId,
"Name" => $this->service,
"EnableTagOverride" => false,
"TaggedAddresses" => [
"lan_ipv4" => [
"address" => "127.0.0.1",
"port" => $rpcPort
],
"wan_ipv4" => [
"address" => Network::local(),
"port" => $rpcPort
]
],
"Check" => [
"CheckId" => "service:rpc.json.{$this->service}." . $this->uniqueId,
"Name" => "service " . $this->service . ' health check',
"Notes" => "Script based health check",
"ServiceID" => $this->service,
"TCP" => $this->checkUrl,
"Interval" => "5s",
"Timeout" => "1s",
"DeregisterCriticalServiceAfter" => "30s"
],
];
if (!empty($this->meta)) {
$defaultConfig["Meta"] = $this->meta;
}
if (!empty($this->tags)) {
$defaultConfig["tags"] = $this->tags;
}
return $defaultConfig;
}
}
+76 -76
View File
@@ -1,76 +1,76 @@
<?php
namespace Kiri\Rpc;
use Exception;
use Kiri\Abstracts\Component;
use Kiri\Context;
use Kiri\Exception\ConfigException;
use Kiri\Kiri;
use Kiri\Pool\Alias;
use Kiri\Pool\Pool;
use Swoole\Client;
/**
*
*/
class ClientPool extends Component
{
const POOL_NAME = 'rpc.client.pool';
use Alias;
public int $max;
public int $min;
public int $waite;
/**
* @param $config
* @param callable $callback
* @return mixed
* @throws ConfigException
* @throws Exception
*/
public function get($config, callable $callback): mixed
{
$coroutineName = $this->name(self::POOL_NAME . '::' . $config['ServiceAddress'] . '::' . $config['ServicePort'], true);
$pool = $config['pool'] ?? ['min' => 1, 'max' => 100];
return $this->getPool()->get($coroutineName, $callback, $pool['min'] ?? 1);
}
/**
* @param \Swoole\Coroutine\Client|Client $client
* @param $host
* @param $port
* @throws ConfigException
* @throws Exception
*/
public function push(\Swoole\Coroutine\Client|Client $client, $host, $port)
{
$coroutineName = $this->name(self::POOL_NAME . '::' . $host . '::' . $port, true);
$this->getPool()->push($coroutineName, $client);
}
/**
* @return Pool
* @throws Exception
*/
public function getPool(): Pool
{
return Kiri::getDi()->get(Pool::class);
}
}
<?php
namespace Kiri\Rpc;
use Exception;
use Kiri\Abstracts\Component;
use Kiri\Context;
use Kiri\Exception\ConfigException;
use Kiri;
use Kiri\Pool\Alias;
use Kiri\Pool\Pool;
use Swoole\Client;
/**
*
*/
class ClientPool extends Component
{
const POOL_NAME = 'rpc.client.pool';
use Alias;
public int $max;
public int $min;
public int $waite;
/**
* @param $config
* @param callable $callback
* @return mixed
* @throws ConfigException
* @throws Exception
*/
public function get($config, callable $callback): mixed
{
$coroutineName = $this->name(self::POOL_NAME . '::' . $config['Address'] . '::' . $config['Port'], true);
$pool = $config['pool'] ?? ['min' => 1, 'max' => 100];
return $this->getPool()->get($coroutineName, $callback, $pool['min'] ?? 1);
}
/**
* @param \Swoole\Coroutine\Client|Client $client
* @param $host
* @param $port
* @throws ConfigException
* @throws Exception
*/
public function push(\Swoole\Coroutine\Client|Client $client, $host, $port)
{
$coroutineName = $this->name(self::POOL_NAME . '::' . $host . '::' . $port, true);
$this->getPool()->push($coroutineName, $client);
}
/**
* @return Pool
* @throws Exception
*/
public function getPool(): Pool
{
return Kiri::getDi()->get(Pool::class);
}
}
@@ -1,23 +1,24 @@
<?php
namespace Kiri\Rpc;
use Throwable;
class InvalidRpcParamsException extends \Exception
{
/**
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = "", $code = 0, Throwable $previous = null)
{
parent::__construct($message, -32602, $previous);
}
}
<?php
namespace Kiri\Rpc;
use JetBrains\PhpStorm\Pure;
use Throwable;
class InvalidRpcParamsException extends \Exception
{
/**
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
#[Pure] public function __construct(string $message = "", int $code = 0, Throwable $previous = null)
{
parent::__construct($message, -32602, $previous);
}
}
+149 -140
View File
@@ -1,140 +1,149 @@
<?php
namespace Kiri\Rpc;
use Exception;
use Http\Message\ServerRequest;
use Http\Message\Stream;
use Kiri\Consul\Agent;
use Kiri\Core\Number;
use Kiri\Kiri;
use Kiri\Pool\Pool;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
*
*/
abstract class JsonRpcConsumers implements OnRpcConsumerInterface
{
/**
* @var Pool
*/
public Pool $pool;
protected string $name = '';
/**
* @param string $method
* @param mixed $data
* @param string $version
* @throws Exception
* @throws ClientExceptionInterface
*/
public function notify(string $method, mixed $data, string $version = '2.0'): void
{
$config = $this->get_consul($this->name);
$transporter = Kiri::getDi()->get(RpcClientInterface::class);
$transporter->withConfig($config)->sendRequest(
$this->requestBody([
'jsonrpc' => $version,
'service' => $this->name,
'method' => $method,
'params' => $data,
])
);
}
/**
* @param array $data
* @return ServerRequestInterface
*/
private function requestBody(array $data): ServerRequestInterface
{
$server = Kiri::getDi()->get(ServerRequest::class);
return $server->withBody(new Stream(json_encode($data)));
}
/**
* @param string $method
* @param mixed $data
* @param string $version
* @param string $id
* @return mixed
* @throws Exception
* @throws ClientExceptionInterface
*/
public function get(string $method, mixed $data, string $version = '2.0', string $id = ''): ResponseInterface
{
if (empty($id)) $id = Number::create(time());
$config = $this->get_consul($this->name);
$transporter = Kiri::getDi()->get(RpcClientInterface::class);
return $transporter->withConfig($config)->sendRequest(
$this->requestBody([
'jsonrpc' => $version,
'service' => $this->name,
'method' => $method,
'params' => $data,
'id' => $id
])
);
}
/**
* @param array $data
* @return mixed
* @throws ClientExceptionInterface
* @throws Exception
*/
public function batch(array $data): mixed
{
$config = $this->get_consul($this->name);
$transporter = Kiri::getDi()->get(RpcClientInterface::class);
return $transporter->withConfig($config)->sendRequest(
$this->requestBody($data)
);
}
/**
* @param $service
* @return array
* @throws Exception
*/
private function get_consul($service): array
{
if (empty($service)) {
throw new Exception('You need set rpc service name if used.');
}
$sf = Kiri::getDi()->get(Agent::class);
$response = $sf->service->setQuery('filter=Service == ' . $service)->list();
if ($response->getStatusCode() != 200 || $response->getBody()->getSize() <= 2) {
throw new Exception('No microservices found [' . $service . '].');
}
$array = [];
$content = json_decode($response->getBody()->getContents(), true);
foreach ($content as $value) {
$array[] = ['id' => $value['ID'], 'Weights' => $value['Weights']['Passing']];
}
if (count($array) < 2) {
$luck = $array[0];
} else {
$luck = Luckdraw::luck($array, 'Weights');
}
return ['Address' => $luck['Address'], 'Port' => $luck['Port']];
}
}
<?php
namespace Kiri\Rpc;
use Exception;
use Kiri\Message\ServerRequest;
use Kiri\Message\Stream;
use Kiri\Core\Number;
use Kiri;
use Kiri\Pool\Pool;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
*
*/
abstract class JsonRpcConsumers implements OnRpcConsumerInterface
{
/**
* @var Pool
*/
public Pool $pool;
protected string $name = '';
/**
* @param string $method
* @param mixed $data
* @param string $version
* @throws Exception
* @throws ClientExceptionInterface
*/
public function notify(string $method, mixed $data, string $version = '2.0'): void
{
$config = $this->get_consul($this->name);
$transporter = Kiri::getDi()->get(RpcClientInterface::class);
$transporter->withConfig($config)->sendRequest(
$this->requestBody([
'jsonrpc' => $version,
'service' => $this->name,
'method' => $method,
'params' => $data,
])
);
}
/**
* @param array $data
* @return ServerRequestInterface
*/
private function requestBody(array $data): ServerRequestInterface
{
$server = Kiri::getDi()->get(ServerRequest::class);
return $server->withBody(new Stream(json_encode($data)));
}
/**
* @param string $method
* @param mixed $data
* @param string $version
* @param string $id
* @return mixed
* @throws Exception
* @throws ClientExceptionInterface
*/
public function get(string $method, mixed $data, string $version = '2.0', string $id = ''): ResponseInterface
{
if (empty($id)) $id = Number::create(time());
$config = $this->get_consul($this->name);
$transporter = Kiri::getDi()->get(RpcClientInterface::class);
return $transporter->withConfig($config)->sendRequest(
$this->requestBody([
'jsonrpc' => $version,
'service' => $this->name,
'method' => $method,
'params' => $data,
'id' => $id
])
);
}
/**
* @param array $data
* @return mixed
* @throws ClientExceptionInterface
* @throws Exception
*/
public function batch(array $data): mixed
{
$config = $this->get_consul($this->name);
$transporter = Kiri::getDi()->get(RpcClientInterface::class);
return $transporter->withConfig($config)->sendRequest(
$this->requestBody($data)
);
}
/**
* @param $service
* @return array
* @throws RpcServiceException|\ReflectionException
* @throws Exception
*/
private function get_consul($service): array
{
if (empty($service)) {
throw new RpcServiceException('You need set rpc service name if used.');
}
$sf = Kiri::getDi()->get(RpcManager::class)->getServices($service);
if (empty($sf) || !is_array($sf)) {
throw new RpcServiceException('You need set rpc service name if used.');
}
return $this->_loadRand($sf);
}
/**
* @param $services
* @return array
*/
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']
];
}
}
@@ -1,68 +1,68 @@
<?php
namespace Kiri\Rpc;
use Note\Inject;
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;
#[Inject(ClientPool::class)]
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();
$response = $this->request($client = $this->getClient(), $content, false);
$this->pool->push($client, $this->config['ServiceAddress'], $this->config['ServicePort']);
return (new Response())->withBody(new Stream($response));
}
/**
* @return Client|\Swoole\Client
* @throws ConfigException
* @throws Exception
*/
private function getClient(): Client|\Swoole\Client
{
$this->config['pool'] = Config::get('rpc.pool', ['max' => 10, 'min' => 1, 'waite' => 60]);
return $this->pool->get($this->config, function () {
return $this->newClient();
});
}
}
<?php
namespace Kiri\Rpc;
use Kiri\Annotation\Inject;
use Exception;
use Kiri\Message\Response;
use Kiri\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;
#[Inject(ClientPool::class)]
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();
$response = $this->request($client = $this->getClient(), $content, false);
$this->pool->push($client, $this->config['Address'], $this->config['Port']);
return (new Response())->withBody(new Stream($response));
}
/**
* @return Client|\Swoole\Client
* @throws ConfigException
* @throws Exception
*/
private function getClient(): Client|\Swoole\Client
{
$this->config['pool'] = Config::get('rpc.pool', ['max' => 10, 'min' => 1, 'waite' => 60]);
return $this->pool->get($this->config, function () {
return $this->newClient();
});
}
}
@@ -1,37 +1,37 @@
<?php
namespace Kiri\Rpc;
use Http\Message\Response;
use Http\Message\Stream;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
*
*/
class JsonRpcTransporter implements ClientInterface
{
use TraitTransporter;
/**
* @param RequestInterface $request
* @return ResponseInterface
* @throws \Exception
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
$content = $request->getBody()->getContents();
$response = $this->request($this->newClient(), $content, true);
return (new Response())->withBody(new Stream($response));
}
}
<?php
namespace Kiri\Rpc;
use Kiri\Message\Response;
use Kiri\Message\Stream;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
*
*/
class JsonRpcTransporter implements ClientInterface
{
use TraitTransporter;
/**
* @param RequestInterface $request
* @return ResponseInterface
* @throws \Exception
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
$content = $request->getBody()->getContents();
$response = $this->request($this->newClient(), $content, true);
return (new Response())->withBody(new Stream($response));
}
}
+201 -201
View File
@@ -1,201 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+151 -151
View File
@@ -1,151 +1,151 @@
<?php
namespace Kiri\Rpc;
use Exception;
class Luckdraw
{
/**
* @param array $goods
* @param string $wight
* @return mixed
* @array = [
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ]
*
* @uses $reward = Lucked::luck($data);
*/
public static function luck(array $goods, string $wight = 'probability'): mixed
{
static $class = null;
if ($class === null) $class = new Luckdraw();
if (empty($goods)) return null;
$array = $prob = $alias = [];
$defaultIndex = 0;
foreach ($goods as $key => $val) {
if ($val[$wight] == 0) $defaultIndex = $key;
$array[] = (float)$val[$wight];
}
$array[$defaultIndex] = 1 - array_sum($array);
$class->ket($array, $prob, $alias);
$result = $class->generation($array, $prob, $alias);
if (!isset($goods[$result])) {
return null;
}
return $goods[$result];
}
/**
* @param $data
* @param $prob
* @param $alias
* @return mixed
*/
private function generation($data, $prob, $alias): mixed
{
$nums = count($prob) - 1;
$MAX_P = $this->getMin($data); // 假设最小的几率是万分之一
$coin_toss = rand(1, $MAX_P) / $MAX_P; // 抛出硬币
$col = rand(0, $nums); // 随机落在一列
$b_head = $coin_toss < $prob[$col]; // 判断是否落在原色
return $b_head ? $col : @$alias[$col];
}
/**
* @param $num
* @return string
*/
private function getMin($num): string
{
$def = current($num);
foreach ($num as $val) {
if ($val < $def) {
$def = $val;
}
}
$length = $this->getFloatLength($def) + 1;
return sprintf('1%0' . $length . 'd', 0);
}
/**
* @param $float
* @return int
*/
private function getFloatLength($float): int
{
$ex = explode('.', 1 - $float);
return strlen(end($ex));
}
/**
* @param array $data
* @param array $prob
* @param array $alias
*/
private function ket(array $data, array &$prob, array &$alias)
{
$nums = count($data);
$small = $large = [];
for ($i = 0; $i < $nums; ++$i) {
$data[$i] = $data[$i] * $nums; // 扩大倍数,使每列高度可为1
/** 分到两个数组,便于组合 */
if ($data[$i] < 1) {
$small[] = $i;
} else {
$large[] = $i;
}
}
/** 将超过1的色块与原色拼凑成1 */
while (!empty($small) && !empty($large)) {
$n_index = array_shift($small);
$a_index = array_shift($large);
$prob[$n_index] = $data[$n_index];
$alias[$n_index] = $a_index;
// 重新调整大色块
$data[$a_index] = ($data[$a_index] + $data[$n_index]) - 1;
if ($data[$a_index] < 1) {
$small[] = $a_index;
} else {
$large[] = $a_index;
}
}
/** 剩下大色块都设为1 */
while (!empty($large)) {
$n_index = array_shift($large);
$prob[$n_index] = 1;
}
/** 一般是精度问题才会执行这一步 */
while (!empty($small)) {
$n_index = array_shift($small);
$prob[$n_index] = 1;
}
}
}
<?php
namespace Kiri\Rpc;
use Exception;
class Luckdraw
{
/**
* @param array $goods
* @param string $wight
* @return mixed
* @array = [
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ['name'=> '商品名称', 'probability'=> '概率', 'total'=> '库存'],
* ]
*
* @uses $reward = Lucked::luck($data);
*/
public static function luck(array $goods, string $wight = 'probability'): mixed
{
static $class = null;
if ($class === null) $class = new Luckdraw();
if (empty($goods)) return null;
$array = $prob = $alias = [];
$defaultIndex = 0;
foreach ($goods as $key => $val) {
if ($val[$wight] == 0) $defaultIndex = $key;
$array[] = (float)$val[$wight];
}
$array[$defaultIndex] = 1 - array_sum($array);
$class->ket($array, $prob, $alias);
$result = $class->generation($array, $prob, $alias);
if (!isset($goods[$result])) {
return null;
}
return $goods[$result];
}
/**
* @param $data
* @param $prob
* @param $alias
* @return mixed
*/
private function generation($data, $prob, $alias): mixed
{
$nums = count($prob) - 1;
$MAX_P = $this->getMin($data); // 假设最小的几率是万分之一
$coin_toss = rand(1, $MAX_P) / $MAX_P; // 抛出硬币
$col = rand(0, $nums); // 随机落在一列
$b_head = $coin_toss < $prob[$col]; // 判断是否落在原色
return $b_head ? $col : @$alias[$col];
}
/**
* @param $num
* @return string
*/
private function getMin($num): string
{
$def = current($num);
foreach ($num as $val) {
if ($val < $def) {
$def = $val;
}
}
$length = $this->getFloatLength($def) + 1;
return sprintf('1%0' . $length . 'd', 0);
}
/**
* @param $float
* @return int
*/
private function getFloatLength($float): int
{
$ex = explode('.', 1 - $float);
return strlen(end($ex));
}
/**
* @param array $data
* @param array $prob
* @param array $alias
*/
private function ket(array $data, array &$prob, array &$alias)
{
$nums = count($data);
$small = $large = [];
for ($i = 0; $i < $nums; ++$i) {
$data[$i] = $data[$i] * $nums; // 扩大倍数,使每列高度可为1
/** 分到两个数组,便于组合 */
if ($data[$i] < 1) {
$small[] = $i;
} else {
$large[] = $i;
}
}
/** 将超过1的色块与原色拼凑成1 */
while (!empty($small) && !empty($large)) {
$n_index = array_shift($small);
$a_index = array_shift($large);
$prob[$n_index] = $data[$n_index];
$alias[$n_index] = $a_index;
// 重新调整大色块
$data[$a_index] = ($data[$a_index] + $data[$n_index]) - 1;
if ($data[$a_index] < 1) {
$small[] = $a_index;
} else {
$large[] = $a_index;
}
}
/** 剩下大色块都设为1 */
while (!empty($large)) {
$n_index = array_shift($large);
$prob[$n_index] = 1;
}
/** 一般是精度问题才会执行这一步 */
while (!empty($small)) {
$n_index = array_shift($small);
$prob[$n_index] = 1;
}
}
}
@@ -1,12 +1,12 @@
<?php
namespace Kiri\Rpc;
interface OnJsonRpcInterface
{
// public function execute();
}
<?php
namespace Kiri\Rpc;
interface OnJsonRpcInterface
{
// public function execute();
}
@@ -1,8 +1,8 @@
<?php
namespace Kiri\Rpc;
interface OnRpcConsumerInterface
{
}
<?php
namespace Kiri\Rpc;
interface OnRpcConsumerInterface
{
}
@@ -1,14 +1,14 @@
<?php
namespace Kiri\Rpc;
use Psr\Http\Client\ClientInterface;
/**
* @mixin JsonRpcTransporter
*/
interface RpcClientInterface extends ClientInterface
{
}
<?php
namespace Kiri\Rpc;
use Psr\Http\Client\ClientInterface;
/**
* @mixin JsonRpcTransporter
*/
interface RpcClientInterface extends ClientInterface
{
}
+281 -261
View File
@@ -1,261 +1,281 @@
<?php
namespace Kiri\Rpc;
use Note\Note;
use Note\Inject;
use Http\Constrict\RequestInterface;
use Http\Handler\Router;
use Http\Message\ServerRequest;
use Kiri\Abstracts\Component;
use Kiri\Abstracts\Config;
use Kiri\Consul\Agent;
use Kiri\Context;
use Kiri\Core\Json;
use Kiri\Events\EventProvider;
use Kiri\Exception\ConfigException;
use Kiri\Kiri;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ServerRequestInterface;
use Server\Contract\OnCloseInterface;
use Server\Contract\OnConnectInterface;
use Server\Contract\OnReceiveInterface;
use Server\Events\OnBeforeShutdown;
use Server\Events\OnStart;
use Swoole\Coroutine;
use Swoole\Coroutine\Channel;
use Swoole\Server;
/**
*
*/
class RpcJsonp extends Component implements OnConnectInterface, OnReceiveInterface, OnCloseInterface
{
#[Inject(Router::class)]
public Router $router;
#[Inject(Note::class)]
public Note $annotation;
#[Inject(EventProvider::class)]
public EventProvider $eventProvider;
#[Inject(ContainerInterface::class)]
public ContainerInterface $container;
/**
*
* @throws \Exception
*/
public function init(): void
{
$this->eventProvider->on(OnBeforeShutdown::class, [$this, 'onBeforeShutdown']);
scan_directory(APP_PATH . 'rpc', 'Rpc');
}
/**
* @param OnBeforeShutdown $beforeShutdown
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function onBeforeShutdown(OnBeforeShutdown $beforeShutdown)
{
$doneList = RpcManager::doneList();
$agent = $this->container->get(Agent::class);
foreach ($doneList as $value) {
$agent->service->deregister($value);
}
}
/**
* @param OnStart $server
* @throws ConfigException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function register(OnStart $server)
{
$config = Config::get('rpc');
$agent = $this->container->get(Agent::class);
$data = $agent->service->register($config['registry']['config']);
if ($data->getStatusCode() != 200) {
$server->server->shutdown();
}
}
/**
* @param Server $server
* @param int $fd
*/
public function onConnect(Server $server, int $fd): void
{
// TODO: Implement onConnect() method.
}
/**
* @param Server $server
* @param int $fd
* @param int $reactor_id
* @param string $data
*/
public function onReceive(Server $server, int $fd, int $reactor_id, string $data): void
{
$data = json_decode($data, true);
if (is_null($data)) {
$this->failure(-32700, 'Parse error语法解析错误');
} else if (!isset($data['jsonrpc']) || !isset($data['method']) || $data['jsonrpc'] != '2.0') {
$this->failure(-32600, 'Invalid Request无效请求');
} else {
$this->batchDispatch($server, $fd, $data);
}
}
/**
* @param Server $server
* @param int $fd
* @param array $data
* @return void
*/
private function batchDispatch(Server $server, int $fd, array $data): void
{
if (isset($data['jsonrpc'])) {
$dispatch = $this->dispatch($data);
if (!isset($data['id'])) {
$dispatch = [1];
}
$result = json_encode($dispatch, JSON_UNESCAPED_UNICODE);
} else {
$channel = new Channel($total = count($data));
foreach ($data as $datum) {
$this->_execute($channel, $datum);
}
$result = [];
for ($i = 0; $i < $total; $i++) {
$result[] = $channel->pop();
}
}
$server->send($fd, json_encode($result, JSON_UNESCAPED_UNICODE));
}
/**
* @param $channel
* @param $datum
*/
private function _execute($channel, $datum)
{
Coroutine::create(function () use ($channel, $datum) {
if (empty($datum) || !isset($datum['jsonrpc'])) {
$channel->push($this->failure(-32700, 'Parse error语法解析错误'));
} else if (!isset($datum['method'])) {
$channel->push($this->failure(-32700, 'Parse error语法解析错误'));
} else {
$dispatch = $this->dispatch($datum);
if (!isset($dispatch['id'])) {
$dispatch = [1];
}
$channel->push($dispatch);
}
});
}
/**
* @param $data
* @return array
*/
private function dispatch($data): array
{
try {
[$handler, $params, $_] = RpcManager::get($data['service'], $data['method']);
if (is_null($handler)) {
throw new \Exception('Method not found', -32601);
} else {
$PsrRequest = Context::setContext(RequestInterface::class, $this->createServerRequest($params));
return $this->handler($handler, $PsrRequest);
}
} catch (\Throwable $throwable) {
$code = $throwable->getCode() == 0 ? -32603 : $throwable->getCode();
return $this->failure($code, jTraceEx($throwable), [], $data['id'] ?? null);
}
}
/**
* @param $params
* @return ServerRequestInterface
* @throws \Exception
*/
private function createServerRequest($params): ServerRequestInterface
{
return (new ServerRequest())->withParsedBody($params);
}
/**
* @param array $handler
* @param $request
* @return array
* @throws \ReflectionException
*/
private function handler(array $handler, $request): array
{
$controller = Kiri::getDi()->get($handler[0]);
$dispatcher = $controller->{$handler[1]}($request);
return [
'jsonrpc' => '2.0',
'result' => $dispatcher,
'id' => $data['id'] ?? null
];
}
/**
* @param $code
* @param $message
* @param array $data
* @param null $id
* @return array
*/
protected function failure($code, $message, array $data = [], $id = null): array
{
$error = [
'jsonrpc' => '2.0',
'error' => [
'code' => $code,
'message' => $message,
'data' => $data
]
];
if (!is_null($id)) {
$error['id'] = $id;
}
return $error;
}
/**
* @param Server $server
* @param int $fd
*/
public function onClose(Server $server, int $fd): void
{
// TODO: Implement onClose() method.
}
}
<?php
namespace Kiri\Rpc;
use Kiri;
use Kiri\Abstracts\Component;
use Kiri\Abstracts\Config;
use Kiri\Annotation\Annotation;
use Kiri\Annotation\Inject;
use Kiri\Consul\Agent;
use Kiri\Context;
use Kiri\Exception\ConfigException;
use Kiri\Message\Constrict\RequestInterface;
use Kiri\Message\Handler\Handler;
use Kiri\Message\Handler\Router;
use Kiri\Message\ServerRequest;
use Kiri\Server\Contract\OnCloseInterface;
use Kiri\Server\Contract\OnConnectInterface;
use Kiri\Server\Contract\OnReceiveInterface;
use Kiri\Server\Events\OnBeforeShutdown;
use Kiri\Server\Events\OnServerBeforeStart;
use Kiri\Server\Events\OnTaskerStart;
use Kiri\Server\Events\OnWorkerExit;
use Kiri\Server\Events\OnWorkerStart;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ServerRequestInterface;
use Swoole\Coroutine;
use Swoole\Coroutine\Channel;
use Swoole\Server;
use Swoole\Timer;
/**
*
*/
class RpcJsonp extends Component implements OnConnectInterface, OnReceiveInterface, OnCloseInterface
{
#[Inject(Router::class)]
public Router $router;
#[Inject(Annotation::class)]
public Annotation $annotation;
private RpcManager $manager;
private int $timerId;
/**
*
* @throws \Exception
*/
public function init(): void
{
$this->getEventProvider()->on(OnBeforeShutdown::class, [$this, 'onBeforeShutdown']);
scan_directory(APP_PATH . 'rpc', 'app\Rpc');
$this->getEventProvider()->on(OnWorkerStart::class, [$this, 'consulWatches']);
$this->getEventProvider()->on(OnWorkerExit::class, [$this, 'onWorkerExit']);
$this->getEventProvider()->on(OnServerBeforeStart::class, [$this, 'register']);
$this->manager = Kiri::getDi()->get(RpcManager::class);
}
/**
* @param OnBeforeShutdown $beforeShutdown
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function onBeforeShutdown(OnBeforeShutdown $beforeShutdown)
{
$doneList = $this->manager->doneList();
$agent = $this->getContainer()->get(Agent::class);
foreach ($doneList as $value) {
$agent->service->deregister($value['config']['ID']);
$agent->checks->deregister($value['config']['Check']['CheckId']);
}
}
/**
* @param OnWorkerStart|OnTaskerStart $server
* @throws ConfigException
*/
public function consulWatches(OnWorkerStart|OnTaskerStart $server)
{
if ($server->workerId != 0) {
return;
}
$async_time = (int)Config::get('consul.async_time', 1000);
$this->timerId = Timer::tick($async_time, static function () {
Kiri::getDi()->get(RpcManager::class)->tick();
});
}
/**
* @param OnWorkerExit $exit
* @return void
*/
public function onWorkerExit(OnWorkerExit $exit)
{
Timer::clear($this->timerId);
}
/**
* @param OnServerBeforeStart $server
*/
public function register(OnServerBeforeStart $server)
{
$this->manager->register();
}
/**
* @param Server $server
* @param int $fd
*/
public function onConnect(Server $server, int $fd): void
{
// TODO: Implement onConnect() method.
}
/**
* @param Server $server
* @param int $fd
* @param int $reactor_id
* @param string $data
*/
public function onReceive(Server $server, int $fd, int $reactor_id, string $data): void
{
$data = json_decode($data, true);
if (is_null($data)) {
$this->failure(-32700, 'Parse error语法解析错误');
} else if (!isset($data['jsonrpc']) || !isset($data['method']) || $data['jsonrpc'] != '2.0') {
$this->failure(-32600, 'Invalid Request无效请求');
} else {
$this->batchDispatch($server, $fd, $data);
}
}
/**
* @param Server $server
* @param int $fd
* @param array $data
* @return void
*/
private function batchDispatch(Server $server, int $fd, array $data): void
{
if (isset($data['jsonrpc'])) {
$dispatch = $this->dispatch($data);
if (!isset($data['id'])) {
$dispatch = [1];
}
$result = json_encode($dispatch, JSON_UNESCAPED_UNICODE);
} else {
$channel = new Channel($total = count($data));
foreach ($data as $datum) {
$this->_execute($channel, $datum);
}
$result = [];
for ($i = 0; $i < $total; $i++) {
$result[] = $channel->pop();
}
}
$server->send($fd, json_encode($result, JSON_UNESCAPED_UNICODE));
}
/**
* @param $channel
* @param $datum
*/
private function _execute($channel, $datum)
{
Coroutine::create(function () use ($channel, $datum) {
if (empty($datum) || !isset($datum['jsonrpc'])) {
$channel->push($this->failure(-32700, 'Parse error语法解析错误'));
} else if (!isset($datum['method'])) {
$channel->push($this->failure(-32700, 'Parse error语法解析错误'));
} else {
$dispatch = $this->dispatch($datum);
if (!isset($dispatch['id'])) {
$dispatch = [1];
}
$channel->push($dispatch);
}
});
}
/**
* @param $data
* @return array
*/
private function dispatch($data): array
{
try {
[$handler, $params] = $this->getContainer()->get(RpcManager::class)->get($data['service'], $data['method']);
if (is_null($handler)) {
throw new \Exception('Method not found', -32601);
} else {
Context::setContext(RequestInterface::class, $this->createServerRequest($params));
return $this->handler($handler);
}
} catch (\Throwable $throwable) {
$code = $throwable->getCode() == 0 ? -32603 : $throwable->getCode();
return $this->failure($code, jTraceEx($throwable), [], $data['id'] ?? null);
}
}
/**
* @param $params
* @return ServerRequestInterface
* @throws \Exception
*/
private function createServerRequest($params): ServerRequestInterface
{
return (new ServerRequest())->withParsedBody($params);
}
/**
* @param Handler $handler
* @return array
*/
private function handler(Handler $handler): array
{
return [
'jsonrpc' => '2.0',
'result' => call_user_func($handler->callback, ...$handler->params),
'id' => $data['id'] ?? null
];
}
/**
* @param $code
* @param $message
* @param array $data
* @param null $id
* @return array
*/
protected function failure($code, $message, array $data = [], $id = null): array
{
$error = [
'jsonrpc' => '2.0',
'error' => [
'code' => $code,
'message' => $message,
'data' => $data
]
];
if (!is_null($id)) {
$error['id'] = $id;
}
return $error;
}
/**
* @param int $fd
*/
public function onClose(int $fd): void
{
// TODO: Implement onClose() method.
}
}
+166
View File
@@ -0,0 +1,166 @@
<?php
namespace Kiri\Rpc;
use Exception;
use Kiri;
use Kiri\Abstracts\Component;
use Kiri\Consul\Agent;
use Kiri\Consul\Health;
use Kiri\Message\Handler\Handler;
use ReflectionException;
class RpcManager extends Component
{
/**
* @var array
*/
private array $_rpc = [];
/**
* @param $serviceName
* @return void
* @throws Exception
*/
public function async($serviceName): void
{
$this->reRegister($serviceName);
$lists = Kiri::getDi()->get(Health::class)->setQuery('passing=true')->service($serviceName);
if ($lists->getStatusCode() != 200) {
return;
}
$body = json_decode($lists->getBody(), true);
$file = storage('.rpc.clients.' . md5($serviceName), 'rpc');
if (!empty($body) && is_array($body)) {
file_put_contents($file, json_encode(array_column($body, 'Service')), LOCK_EX);
} else {
file_put_contents($file, json_encode([]), LOCK_EX);
}
}
/**
* @param string $serviceName
* @return void
* @throws Exception
*/
public function reRegister(string $serviceName)
{
$config = $this->_rpc[$serviceName] ?? [];
if (empty($config)) {
return;
}
$service = Kiri::getDi()->get(Agent::class);
$info = $service->service->service_health($config['config']['ID']);
if ($info->getStatusCode() == 200) {
return;
}
$service->service->register($config['config']);
}
/**
* @throws Exception
*/
public function tick(): void
{
try {
foreach ($this->_rpc as $name => $list) {
$this->async($name);
}
} catch (\Throwable $throwable) {
$this->logger()->error(error_trigger_format($throwable));
}
}
/**
* @param $serviceName
* @return array
* @throws Exception
*/
public function getServices($serviceName): array
{
$file = storage('.rpc.clients.' . md5($serviceName), 'rpc');
if (!file_exists($file) || filesize($file) < 10) {
$this->async($serviceName);
}
$content = json_decode(file_get_contents($file), true);
if (empty($content) || !is_array($content)) {
return [];
}
return $content;
}
/**
* @param string $name
* @param string $class
* @param array $serviceConfig
* @return bool
* @throws ReflectionException
*/
public function add(string $name, string $class, array $serviceConfig): bool
{
$methods = Kiri::getDi()->getReflect($class);
$lists = $methods->getMethods(\ReflectionMethod::IS_PUBLIC);
if (!isset($this->_rpc[$name])) {
$this->_rpc[$name] = ['methods' => [], 'id' => $serviceConfig['ID'], 'config' => $serviceConfig];
}
foreach ($lists as $reflection) {
if ($reflection->getDeclaringClass() != $class) {
continue;
}
$methodName = $reflection->getName();
$this->_rpc[$name]['methods'][$methodName] = [new Handler('/', [$class, $methodName]), null];
}
return true;
}
/**
* @return array
*/
public function doneList(): array
{
$array = [];
foreach ($this->_rpc as $list) {
$array[] = $list;
}
return $array;
}
/**
*/
public function register()
{
$agent = Kiri::getDi()->get(Agent::class);
foreach ($this->_rpc as $list) {
$agent->service->deregister($list['config']['ID']);
$data = $agent->service->register($list['config']);
if ($data->getStatusCode() != 200) {
return;
}
}
}
/**
* @param string $name
* @param string $method
* @return mixed
*/
public function get(string $name, string $method): array
{
return $this->_rpc[$name]['methods'][$method] ?? [null, null];
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace Kiri\Rpc;
class RpcServiceException extends \Exception
{
}
@@ -1,78 +1,78 @@
<?php
namespace Kiri\Rpc;
use Exception;
use Kiri\Context;
use Swoole\Client;
use Swoole\Coroutine;
trait TraitTransporter
{
protected array $config;
protected array $clients = [];
/**
* @param $config
* @return $this
*/
public function withConfig($config): static
{
$this->config = $config;
return $this;
}
/**
* @param Client|Coroutine\Client $client
* @param $content
* @param bool $isClose
* @return mixed
*/
private function request(Client|Coroutine\Client $client, $content, bool $isClose): mixed
{
$client->send($content);
$read = $client->recv();
if ($isClose) {
$client->close();
}
return $read;
}
/**
* @return Client|Coroutine\Client
* @throws Exception
*/
private function newClient(): Coroutine\Client|Client
{
$alias = $this->alias($this->config);
$client = $this->clients[$alias] ?? null;
if (is_null($client)) {
$client = Context::inCoroutine() ? new Coroutine\Client(SWOOLE_SOCK_TCP) : new Client(SWOOLE_SOCK_TCP);
$this->clients[$alias] = $client;
}
[$host, $port] = [$this->config['ServiceAddress'], $this->config['ServicePort']];
if (!$client->isConnected() && !$client->connect($host, $port, 60)) {
throw new Exception('connect fail.');
}
return $client;
}
/**
* @param array $config
* @return string
*/
private function alias(array $config): string
{
return $config['ServiceAddress'] . '::' . $config['ServicePort'];
}
}
<?php
namespace Kiri\Rpc;
use Exception;
use Kiri\Context;
use Swoole\Client;
use Swoole\Coroutine;
trait TraitTransporter
{
protected array $config;
protected array $clients = [];
/**
* @param $config
* @return $this
*/
public function withConfig($config): static
{
$this->config = $config;
return $this;
}
/**
* @param Client|Coroutine\Client $client
* @param $content
* @param bool $isClose
* @return mixed
*/
private function request(Client|Coroutine\Client $client, $content, bool $isClose): mixed
{
$client->send($content);
$read = $client->recv();
if ($isClose) {
$client->close();
}
return $read;
}
/**
* @return Client|Coroutine\Client
* @throws Exception
*/
private function newClient(): Coroutine\Client|Client
{
$alias = $this->alias($this->config);
$client = $this->clients[$alias] ?? null;
if (is_null($client)) {
$client = Context::inCoroutine() ? new Coroutine\Client(SWOOLE_SOCK_TCP) : new Client(SWOOLE_SOCK_TCP);
$this->clients[$alias] = $client;
}
[$host, $port] = [$this->config['Address'], $this->config['Port']];
if (!$client->isConnected() && !$client->connect($host, $port, 60)) {
throw new Exception('connect fail.');
}
return $client;
}
/**
* @param array $config
* @return string
*/
private function alias(array $config): string
{
return $config['Address'] . '::' . $config['Port'];
}
}
+23 -24
View File
@@ -1,24 +1,23 @@
{
"name": "game-worker/kiri-rpc",
"description": "kiri-rpc",
"authors": [
{
"name": "XiangLin",
"email": "as2252258@163.com"
}
],
"license": "MIT",
"require": {
"php": ">=8.0",
"ext-json": "*",
"psr/http-client": "^1.0",
"psr/http-message": "^1.0"
},
"autoload": {
"psr-4": {
"Kiri\\Rpc\\": "src/"
}
},
"require-dev": {
}
}
{
"name": "game-worker/kiri-rpc",
"description": "kiri-rpc",
"authors": [
{
"name": "XiangLin",
"email": "as2252258@163.com"
}
],
"license": "MIT",
"require": {
"php": ">=8.0",
"ext-json": "*",
"psr/http-client": "^1.0"
},
"autoload": {
"psr-4": {
"Kiri\\Rpc\\": "./"
}
},
"require-dev": {
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
use Kiri\Rpc\RpcJsonp;
use Kiri\Rpc\TestRpcService;
use Kiri\Server\Constant;
return [
'rpc' => [
'name' => 'json-rpc',
'type' => Constant::SERVER_TYPE_BASE,
'mode' => SWOOLE_SOCK_TCP,
'host' => '0.0.0.0',
'port' => 9526,
'settings' => [
],
'events' => [
Constant::RECEIVE => [RpcJsonp::class, 'onReceive']
],
'consumers' => [
'class' => TestRpcService::class,
'name' => 'test-rpc',
'package' => 'test',
'register' => [
'host' => '',
'port' => ''
]
]
],
'service' => [
[
"datacenter" => "dc1",
"id" => "40e4a748-2192-161a-0510-9bf59fe950b5",
"node" => "FriendRpcService",
"skipNodeUpdate" => false,
"service" => [
"id" => "redis1",
"service" => "FriendRpcService",
"address" => "172.26.221.211",
"taggedAddresses" => [
"lan" => [
"address" => "127.0.0.1",
"port" => 8000
],
"wan" => [
"address" => "172.26.221.211",
"port" => 80
]
],
"meta" => [
"redis_version" => "4.0"
],
"port" => 8000
],
"check" => [
"node" => "t2.320",
"checkId" => "service:redis1",
"name" => "Redis health check",
"Annotations" => "Script based health check",
"status" => "passing",
"serviceID" => "redis1",
"definition" => [
"http" => "172.26.221.211:9527",
"interval" => "5s",
"timeout" => "1s",
"deregisterCriticalServiceAfter" => "30s"
],
],
]
]
];
-74
View File
@@ -1,74 +0,0 @@
<?php
namespace Kiri\Rpc\Note;
use Note\Attribute;
use Kiri\Abstracts\Config;
use Kiri\Consul\Agent;
use Kiri\Exception\ConfigException;
use Kiri\Kiri;
use Kiri\Rpc\RpcManager;
use ReflectionException;
#[\Attribute(\Attribute::TARGET_CLASS)] class JsonRpc extends Attribute
{
/**
* @param string $service
* @param string $driver
* @param array $checkOptions
*/
public function __construct(public string $service, public string $driver, public array $checkOptions = [
"DeregisterCriticalServiceAfter" => "1m",
"Http" => "http://127.0.0.1:9527",
"Interval" => "1s",
"Timeout" => "1s"
])
{
}
/**
* @param mixed $class
* @param mixed|string $method
* @return mixed
* @throws ReflectionException
* @throws ConfigException
*/
public function execute(mixed $class, mixed $method = ''): bool
{
$default = $this->create();
$agent = Kiri::getDi()->get(Agent::class);
$data = $agent->service->register($default);
if ($data->getStatusCode() != 200) {
exit($data->getBody()->getContents());
}
return RpcManager::add($this->service, $class, $default['id']);
}
/**
* @throws ConfigException
*/
protected function create(): array
{
$content = current(swoole_get_local_ip());
return [
"id" => "rpc.json.{$this->service}." . md5(__DIR__ . '.' . md5($content)),
"name" => $this->service,
"address" => $content,
"port" => 9526,
"enableTagOverride" => true,
"check" => [
"DeregisterCriticalServiceAfter" => "1m",
"TCP" => $content . ":" . Config::get('rpc.port'),
"Interval" => "1s",
"Timeout" => "1s"
]
];
}
}
-64
View File
@@ -1,64 +0,0 @@
<?php
namespace Kiri\Rpc;
use Kiri\Kiri;
use ReflectionException;
class RpcManager
{
/**
* @var array
*/
private static array $_rpc = [];
/**
* @param string $name
* @param string $class
* @param string $serviceId
* @return bool
* @throws ReflectionException
*/
public static function add(string $name, string $class, string $serviceId): bool
{
$methods = Kiri::getDi()->getReflect($class);
$lists = $methods->getMethods(\ReflectionMethod::IS_PUBLIC);
if (!isset(static::$_rpc[$name])) static::$_rpc[$name] = ['methods' => [], 'id' => $serviceId];
foreach ($lists as $reflection) {
$methodName = $reflection->getName();
static::$_rpc[$name]['methods'][$methodName] = [[$class, $methodName], null];
}
return true;
}
/**
* @return array
*/
public static function doneList(): array
{
$array = [];
foreach (static::$_rpc as $list) {
$array[] = $list['id'];
}
return $array;
}
/**
* @param string $name
* @param string $method
* @return mixed
*/
public static function get(string $name, string $method): array
{
return static::$_rpc[$name]['methods'][$method] ?? [null, null];
}
}
-33
View File
@@ -1,33 +0,0 @@
<?php
use Kiri\Rpc\RpcJsonp;
use Kiri\Rpc\TestRpcService;
use Server\Constant;
return [
'rpc' => [
'name' => 'json-rpc',
'type' => Constant::SERVER_TYPE_BASE,
'mode' => SWOOLE_SOCK_TCP,
'host' => '0.0.0.0',
'port' => 9526,
'settings' => [
],
'events' => [
Constant::RECEIVE => [RpcJsonp::class, 'onReceive']
],
'consumers' => [
'class' => TestRpcService::class,
'name' => 'test-rpc',
'package' => 'test',
'register' => [
'host' => '',
'port' => ''
]
]
]
];