Compare commits
96 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6926a636b4 | |||
| fe09da4a97 | |||
| cab1ed999a | |||
| 349e07b12c | |||
| 5fb1f0fc99 | |||
| 524d2b8664 | |||
| f4a5a4dbee | |||
| af613784fd | |||
| 6418b3288b | |||
| a761bb3428 | |||
| 2ecb13c453 | |||
| 0a705b27bc | |||
| 10a64ee646 | |||
| 493a58281f | |||
| 18a9b29bbd | |||
| d72ff2f82c | |||
| de2698ee12 | |||
| b1bc0ff23c | |||
| 7f28443d99 | |||
| 7ea28f47e1 | |||
| c01dc5f41a | |||
| c190c749f4 | |||
| 45315dcbb2 | |||
| 8d20f56660 | |||
| 348f0129e8 | |||
| 6371d5271e | |||
| 8f9de7a508 | |||
| 2a6b2a1979 | |||
| b79513757b | |||
| b495927099 | |||
| 188742360e | |||
| 6715743843 | |||
| f94a8a3792 | |||
| 0ad17ae4c5 | |||
| 95772e794b | |||
| 9473384c18 | |||
| 152049fdae | |||
| 4c6739a83b | |||
| 5f81fd5ff9 | |||
| cf8208bd12 | |||
| 0d2989171e | |||
| 4b50c3fc18 | |||
| ad346d01d1 | |||
| c108de48af | |||
| 3192b5940e | |||
| 1d3b71b023 | |||
| abaa2547f7 | |||
| c982e44631 | |||
| 87d47e0971 | |||
| 072db59b9f | |||
| 2620e88447 | |||
| f3cd9b4b7c | |||
| e270f9c588 | |||
| f2cf841573 | |||
| 7a3299cb10 | |||
| 2ad3809736 | |||
| 219d246d4a | |||
| a3dfcf02e6 | |||
| 688b2381da | |||
| 8824f711bb | |||
| f2d97832b5 | |||
| 855e57a651 | |||
| 0b3310b82e | |||
| e8cf7f29f0 | |||
| 62e3b001f0 | |||
| f655cebdf3 | |||
| ee492d97ad | |||
| a16d841d98 | |||
| f015662fd6 | |||
| 021dcae59b | |||
| c6dc34c821 | |||
| 88c3958aba | |||
| 24ebfac360 | |||
| b3c200b443 | |||
| 3e2b50bf60 | |||
| 89c142930e | |||
| 1515d9695c | |||
| f1f7b1081d | |||
| 07533e29f9 | |||
| 4d60a24fac | |||
| 4dc6bc661a | |||
| 0d7fd5e356 | |||
| da16b0685d | |||
| febbdea8c8 | |||
| a45c3d875c | |||
| 64d01c0a80 | |||
| bf5fe594e4 | |||
| 5cfe3c6d6d | |||
| 773e3c0f57 | |||
| b1c91343ef | |||
| 3f821ca9d0 | |||
| d296b3107e | |||
| f606c58204 | |||
| 6c1d986814 | |||
| da056b09c7 | |||
| 4eefe54be0 |
+37
-37
@@ -1,37 +1,37 @@
|
|||||||
# Created by .ignore support plugin (hsz.mobi)
|
# Created by .ignore support plugin (hsz.mobi)
|
||||||
### Yii template
|
### Yii template
|
||||||
assets/*
|
assets/*
|
||||||
!assets/.gitignore
|
!assets/.gitignore
|
||||||
protected/runtime/*
|
protected/runtime/*
|
||||||
!protected/runtime/.gitignore
|
!protected/runtime/.gitignore
|
||||||
protected/data/*.db
|
protected/data/*.db
|
||||||
themes/classic/views/
|
themes/classic/views/
|
||||||
|
|
||||||
### Example user template template
|
### Example user template template
|
||||||
### Example user template
|
### Example user template
|
||||||
|
|
||||||
# IntelliJ project files
|
# IntelliJ project files
|
||||||
.idea
|
.idea
|
||||||
*.iml
|
*.iml
|
||||||
out
|
out
|
||||||
gen
|
gen
|
||||||
|
|
||||||
db/
|
db/
|
||||||
async-queue/
|
async-queue/
|
||||||
|
|
||||||
composer.lock
|
composer.lock
|
||||||
|
|
||||||
*.log
|
*.log
|
||||||
commands/result
|
commands/result
|
||||||
config/setting.php
|
config/setting.php
|
||||||
tests/
|
tests/
|
||||||
vendor/
|
vendor/
|
||||||
runtime/
|
runtime/
|
||||||
|
|
||||||
*.xml
|
*.xml
|
||||||
*.lock
|
*.lock
|
||||||
|
|
||||||
oot
|
oot
|
||||||
d
|
d
|
||||||
|
|
||||||
composer.lock
|
composer.lock
|
||||||
|
|||||||
+18
-18
@@ -1,18 +1,18 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace PHPSTORM_META {
|
namespace PHPSTORM_META {
|
||||||
|
|
||||||
// Reflect
|
// Reflect
|
||||||
use Kiri\Di\Container;
|
use Kiri\Di\Container;
|
||||||
use Psr\Container\ContainerInterface;
|
use Kiri\Di\ContainerInterface;
|
||||||
|
|
||||||
override(ContainerInterface::get(0), map('@'));
|
override(ContainerInterface::get(0), map('@'));
|
||||||
override(Container::get(0), map('@'));
|
override(Container::get(0), map('@'));
|
||||||
override(Container::make(0), map('@'));
|
override(Container::make(0), map('@'));
|
||||||
override(Container::create(0), map('@'));
|
override(Container::create(0), map('@'));
|
||||||
// override(\Hyperf\Utils\Context::get(0), map('@'));
|
// override(\Hyperf\Utils\Context::get(0), map('@'));
|
||||||
// override(\make(0), map('@'));
|
// override(\make(0), map('@'));
|
||||||
override(\di(0), map('@'));
|
override(\di(0), map('@'));
|
||||||
override(\duplicate(0), map('@'));
|
override(\duplicate(0), map('@'));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
|
use Kiri\Core\Json;
|
||||||
|
use Kiri\Core\Number;
|
||||||
|
use Kiri\Di\Inject\Container;
|
||||||
|
|
||||||
|
abstract class AbstractRpcClient
|
||||||
|
{
|
||||||
|
|
||||||
|
|
||||||
|
public string $service = '';
|
||||||
|
|
||||||
|
|
||||||
|
public string $version = '';
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var JsonRpcTransporterInterface
|
||||||
|
*/
|
||||||
|
#[Container(JsonRpcTransporterInterface::class)]
|
||||||
|
private JsonRpcTransporterInterface $transporter;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param JsonRpcTransporterInterface $transporter
|
||||||
|
*/
|
||||||
|
public function setTransporter(JsonRpcTransporterInterface $transporter): void
|
||||||
|
{
|
||||||
|
$this->transporter = $transporter;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getService(): string
|
||||||
|
{
|
||||||
|
if (empty($this->service)) {
|
||||||
|
return get_called_class();
|
||||||
|
}
|
||||||
|
return $this->service;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $method
|
||||||
|
* @param ...$args
|
||||||
|
* @return string|bool
|
||||||
|
*/
|
||||||
|
protected function send(string $method, ...$args): string|bool
|
||||||
|
{
|
||||||
|
$result = $this->transporter->push(Json::encode([
|
||||||
|
'jsonrpc' => $this->version,
|
||||||
|
'service' => $this->getService(),
|
||||||
|
'method' => $method,
|
||||||
|
'params' => $args,
|
||||||
|
'id' => Number::create(time())
|
||||||
|
]), $this->getService());
|
||||||
|
if (is_string($result)) {
|
||||||
|
return json_decode($result, true);
|
||||||
|
} else {
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Kiri\Rpc\Annotation;
|
|
||||||
|
|
||||||
use Kiri\Abstracts\Config;
|
|
||||||
use Kiri\Core\Network;
|
|
||||||
use Kiri\Exception\ConfigException;
|
|
||||||
use Kiri\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',
|
|
||||||
"Annotations" => "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;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
+114
-76
@@ -1,76 +1,114 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
use Exception;
|
use Exception;
|
||||||
use Kiri\Abstracts\Component;
|
use Kiri;
|
||||||
use Kiri\Context;
|
use Kiri\Abstracts\Component;
|
||||||
use Kiri\Exception\ConfigException;
|
use Kiri\Pool\Pool;
|
||||||
use Kiri\Kiri;
|
use Kiri\Server\Events\OnBeforeShutdown;
|
||||||
use Kiri\Pool\Alias;
|
use ReflectionException;
|
||||||
use Kiri\Pool\Pool;
|
use Swoole\Coroutine\Client as CoroutineClient;
|
||||||
use Swoole\Client;
|
use Swoole\Client as AsyncClient;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
class ClientPool extends Component
|
class ClientPool extends Component
|
||||||
{
|
{
|
||||||
|
|
||||||
const POOL_NAME = 'rpc.client.pool';
|
public int $max;
|
||||||
|
|
||||||
use Alias;
|
|
||||||
|
public int $min;
|
||||||
|
|
||||||
public int $max;
|
|
||||||
|
private array $names = [];
|
||||||
|
|
||||||
public int $min;
|
|
||||||
|
/**
|
||||||
|
* @return void
|
||||||
public int $waite;
|
*/
|
||||||
|
public function init(): void
|
||||||
|
{
|
||||||
/**
|
on(OnBeforeShutdown::class, [$this, 'onBeforeShutdown']);
|
||||||
* @param $config
|
}
|
||||||
* @param callable $callback
|
|
||||||
* @return mixed
|
|
||||||
* @throws ConfigException
|
/**
|
||||||
* @throws Exception
|
* @return void
|
||||||
*/
|
* @throws Exception
|
||||||
public function get($config, callable $callback): mixed
|
*/
|
||||||
{
|
public function onBeforeShutdown(): void
|
||||||
$coroutineName = $this->name(self::POOL_NAME . '::' . $config['Address'] . '::' . $config['Port'], true);
|
{
|
||||||
|
$pool = Kiri::getDi()->get(Pool::class);
|
||||||
$pool = $config['pool'] ?? ['min' => 1, 'max' => 100];
|
foreach ($this->names as $name) {
|
||||||
|
$pool->clean($name);
|
||||||
return $this->getPool()->get($coroutineName, $callback, $pool['min'] ?? 1);
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param \Swoole\Coroutine\Client|Client $client
|
* @param $config
|
||||||
* @param $host
|
* @return resource
|
||||||
* @param $port
|
* @throws Exception
|
||||||
* @throws ConfigException
|
*/
|
||||||
* @throws Exception
|
public function get($config): mixed
|
||||||
*/
|
{
|
||||||
public function push(\Swoole\Coroutine\Client|Client $client, $host, $port)
|
$coroutineName = $config['Address'] . '::' . $config['Port'];
|
||||||
{
|
|
||||||
$coroutineName = $this->name(self::POOL_NAME . '::' . $host . '::' . $port, true);
|
if (!in_array($coroutineName, $this->names)) {
|
||||||
|
$this->names[] = $coroutineName;
|
||||||
$this->getPool()->push($coroutineName, $client);
|
}
|
||||||
}
|
|
||||||
|
return $this->getPool($config['Address'], $config['Port'])->get($coroutineName);
|
||||||
|
}
|
||||||
/**
|
|
||||||
* @return Pool
|
|
||||||
* @throws Exception
|
/**
|
||||||
*/
|
* @param CoroutineClient|AsyncClient $client
|
||||||
public function getPool(): Pool
|
* @param $host
|
||||||
{
|
* @param $port
|
||||||
return Kiri::getDi()->get(Pool::class);
|
* @throws Exception
|
||||||
}
|
*/
|
||||||
|
public function push(CoroutineClient|AsyncClient $client, $host, $port)
|
||||||
}
|
{
|
||||||
|
$this->getPool($host, $port)->push($host . '::' . $port, $client);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $host
|
||||||
|
* @param int $port
|
||||||
|
* @return Pool
|
||||||
|
* @throws ReflectionException
|
||||||
|
*/
|
||||||
|
public function getPool(string $host, int $port): Pool
|
||||||
|
{
|
||||||
|
$pool = Kiri::getDi()->get(Pool::class);
|
||||||
|
$pool->created($host . '::' . $port, 10, [$this, 'connect']);
|
||||||
|
return $pool;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Etcd\Client;
|
||||||
|
use GuzzleHttp\Exception\BadResponseException;
|
||||||
|
use Kiri\Abstracts\Component;
|
||||||
|
use Kiri\Core\Str;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
class Etcd extends Component
|
||||||
|
{
|
||||||
|
|
||||||
|
|
||||||
|
private Client $client;
|
||||||
|
|
||||||
|
|
||||||
|
private bool $isEnd = false;
|
||||||
|
|
||||||
|
|
||||||
|
private array $config = [];
|
||||||
|
|
||||||
|
|
||||||
|
private array|BadResponseException $grant;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return void
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
public function init(): void
|
||||||
|
{
|
||||||
|
$this->client = new Client('47.92.194.207:' . 2379, 'v3');
|
||||||
|
$this->grant = $this->client->grant(60);
|
||||||
|
if ($this->grant instanceof BadResponseException) {
|
||||||
|
throw new Exception($this->grant->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
$key = 'center.service.' . gethostbyname(gethostname());
|
||||||
|
\pcntl_signal(SIGINT, function () use ($key) {
|
||||||
|
$this->isEnd = true;
|
||||||
|
$this->client->del($key);
|
||||||
|
});
|
||||||
|
$this->client->put($key, json_encode([
|
||||||
|
'address' => gethostbyname(gethostname()) . ':10240',
|
||||||
|
'nodeId' => Str::rand(32)
|
||||||
|
]), ['lease' => (int)$this->grant["ID"]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $key
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public function get(string $key): mixed
|
||||||
|
{
|
||||||
|
return $this->config[$key] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $key
|
||||||
|
* @param mixed $value
|
||||||
|
* @return void
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
public function put(string $key, mixed $value): void
|
||||||
|
{
|
||||||
|
$result = $this->client->put($key, $value);
|
||||||
|
if ($result instanceof BadResponseException) {
|
||||||
|
throw new Exception($result->getMessage());
|
||||||
|
}
|
||||||
|
$this->config[$key] = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function waite(): void
|
||||||
|
{
|
||||||
|
while ($this->isEnd == false) {
|
||||||
|
$this->client->keepAlive((int)$this->grant["ID"]);
|
||||||
|
sleep(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,23 +1,24 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
use Throwable;
|
use JetBrains\PhpStorm\Pure;
|
||||||
|
use Throwable;
|
||||||
class InvalidRpcParamsException extends \Exception
|
|
||||||
{
|
class InvalidRpcParamsException extends \Exception
|
||||||
|
{
|
||||||
|
|
||||||
/**
|
|
||||||
* @param string $message
|
/**
|
||||||
* @param int $code
|
* @param string $message
|
||||||
* @param Throwable|null $previous
|
* @param int $code
|
||||||
*/
|
* @param Throwable|null $previous
|
||||||
public function __construct($message = "", $code = 0, Throwable $previous = null)
|
*/
|
||||||
{
|
#[Pure] public function __construct(string $message = "", int $code = 0, Throwable $previous = null)
|
||||||
parent::__construct($message, -32602, $previous);
|
{
|
||||||
}
|
parent::__construct($message, -32602, $previous);
|
||||||
|
}
|
||||||
}
|
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,150 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
|
||||||
|
|
||||||
|
|
||||||
use Exception;
|
|
||||||
use Http\Message\ServerRequest;
|
|
||||||
use Http\Message\Stream;
|
|
||||||
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
|
|
||||||
* @throws \ReflectionException
|
|
||||||
*/
|
|
||||||
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']
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
+49
-68
@@ -1,68 +1,49 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
use Kiri\Annotation\Inject;
|
use Exception;
|
||||||
use Exception;
|
use Kiri\Di\Inject\Container;
|
||||||
use Http\Message\Response;
|
use Kiri\Exception\ConfigException;
|
||||||
use Http\Message\Stream;
|
use ReflectionException;
|
||||||
use Kiri\Abstracts\Config;
|
|
||||||
use Kiri\Exception\ConfigException;
|
class JsonRpcPoolTransporter implements JsonRpcTransporterInterface
|
||||||
use Psr\Http\Client\ClientInterface;
|
{
|
||||||
use Psr\Http\Message\RequestInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Swoole\Coroutine\Client;
|
use TraitTransporter;
|
||||||
|
|
||||||
class JsonRpcPoolTransporter implements ClientInterface
|
|
||||||
{
|
#[Container(ClientPool::class)]
|
||||||
|
public ClientPool $pool;
|
||||||
|
|
||||||
use TraitTransporter;
|
|
||||||
|
/**
|
||||||
|
* @param string $content
|
||||||
#[Inject(ClientPool::class)]
|
* @param string $service
|
||||||
public ClientPool $pool;
|
* @return string|bool
|
||||||
|
* @throws RpcServiceException
|
||||||
|
* @throws ReflectionException
|
||||||
const POOL_NAME = 'rpc.client.pool';
|
*/
|
||||||
|
public function push(string $content, string $service): string|bool
|
||||||
|
{
|
||||||
/**
|
$client = $this->get_consul($service)->getClient();
|
||||||
*/
|
|
||||||
public function init()
|
$response = $this->request($client, $content);
|
||||||
{
|
|
||||||
}
|
$this->pool->push($client, $this->config['Address'], $this->config['Port']);
|
||||||
|
|
||||||
|
return $response;
|
||||||
/**
|
}
|
||||||
* @param RequestInterface $request
|
|
||||||
* @return ResponseInterface
|
|
||||||
* @throws Exception
|
/**
|
||||||
*/
|
* @throws Exception
|
||||||
public function sendRequest(RequestInterface $request): ResponseInterface
|
*/
|
||||||
{
|
private function getClient()
|
||||||
$content = $request->getBody()->getContents();
|
{
|
||||||
|
return $this->pool->get($this->config);
|
||||||
$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();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|||||||
+37
-37
@@ -1,37 +1,37 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
use Http\Message\Response;
|
use Exception;
|
||||||
use Http\Message\Stream;
|
|
||||||
use Psr\Http\Client\ClientInterface;
|
|
||||||
use Psr\Http\Message\RequestInterface;
|
/**
|
||||||
use Psr\Http\Message\ResponseInterface;
|
*
|
||||||
|
*/
|
||||||
|
class JsonRpcTransporter implements JsonRpcTransporterInterface
|
||||||
/**
|
{
|
||||||
*
|
|
||||||
*/
|
|
||||||
class JsonRpcTransporter implements ClientInterface
|
use TraitTransporter;
|
||||||
{
|
|
||||||
|
|
||||||
|
/**
|
||||||
use TraitTransporter;
|
* @param string $content
|
||||||
|
* @param string $service
|
||||||
|
* @return string|bool
|
||||||
/**
|
* @throws RpcServiceException
|
||||||
* @param RequestInterface $request
|
* @throws Exception
|
||||||
* @return ResponseInterface
|
*/
|
||||||
* @throws \Exception
|
public function push(string $content, string $service): string|bool
|
||||||
*/
|
{
|
||||||
public function sendRequest(RequestInterface $request): ResponseInterface
|
$client = $this->get_consul($service)->newClient();
|
||||||
{
|
|
||||||
$content = $request->getBody()->getContents();
|
$body = $this->request($client, $content);
|
||||||
|
|
||||||
$response = $this->request($this->newClient(), $content, true);
|
$client->close();
|
||||||
|
|
||||||
return (new Response())->withBody(new Stream($response));
|
return $body;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
|
interface JsonRpcTransporterInterface
|
||||||
|
{
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $content
|
||||||
|
* @param string $service
|
||||||
|
* @return string|bool
|
||||||
|
*/
|
||||||
|
public function push(string $content, string $service): string|bool;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,201 +1,201 @@
|
|||||||
Apache License
|
Apache License
|
||||||
Version 2.0, January 2004
|
Version 2.0, January 2004
|
||||||
http://www.apache.org/licenses/
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
1. Definitions.
|
1. Definitions.
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction,
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
and distribution as defined by Sections 1 through 9 of this document.
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
the copyright owner that is granting the License.
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
other entities that control, are controlled by, or are under common
|
other entities that control, are controlled by, or are under common
|
||||||
control with that entity. For the purposes of this definition,
|
control with that entity. For the purposes of this definition,
|
||||||
"control" means (i) the power, direct or indirect, to cause the
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
direction or management of such entity, whether by contract or
|
direction or management of such entity, whether by contract or
|
||||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
exercising permissions granted by this License.
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications,
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
including but not limited to software source code, documentation
|
including but not limited to software source code, documentation
|
||||||
source, and configuration files.
|
source, and configuration files.
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical
|
"Object" form shall mean any form resulting from mechanical
|
||||||
transformation or translation of a Source form, including but
|
transformation or translation of a Source form, including but
|
||||||
not limited to compiled object code, generated documentation,
|
not limited to compiled object code, generated documentation,
|
||||||
and conversions to other media types.
|
and conversions to other media types.
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
Object form, made available under the License, as indicated by a
|
Object form, made available under the License, as indicated by a
|
||||||
copyright notice that is included in or attached to the work
|
copyright notice that is included in or attached to the work
|
||||||
(an example is provided in the Appendix below).
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object
|
"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
|
form, that is based on (or derived from) the Work and for which the
|
||||||
editorial revisions, annotations, elaborations, or other modifications
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
represent, as a whole, an original work of authorship. For the purposes
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
of this License, Derivative Works shall not include works that remain
|
of this License, Derivative Works shall not include works that remain
|
||||||
separable from, or merely link (or bind by name) to the interfaces of,
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
the Work and Derivative Works thereof.
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including
|
"Contribution" shall mean any work of authorship, including
|
||||||
the original version of the Work and any modifications or additions
|
the original version of the Work and any modifications or additions
|
||||||
to that Work or Derivative Works thereof, that is intentionally
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
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
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
the copyright owner. For the purposes of this definition, "submitted"
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
means any form of electronic, verbal, or written communication sent
|
means any form of electronic, verbal, or written communication sent
|
||||||
to the Licensor or its representatives, including but not limited to
|
to the Licensor or its representatives, including but not limited to
|
||||||
communication on electronic mailing lists, source code control systems,
|
communication on electronic mailing lists, source code control systems,
|
||||||
and issue tracking systems that are managed by, or on behalf of, the
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
Licensor for the purpose of discussing and improving the Work, but
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
excluding communication that is conspicuously marked or otherwise
|
excluding communication that is conspicuously marked or otherwise
|
||||||
designated in writing by the copyright owner as "Not a Contribution."
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
on behalf of whom a Contribution has been received by Licensor and
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
subsequently incorporated within the Work.
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
copyright license to reproduce, prepare Derivative Works of,
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
publicly display, publicly perform, sublicense, and distribute the
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
Work and such Derivative Works in Source or Object form.
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
(except as stated in this section) patent license to make, have made,
|
(except as stated in this section) patent license to make, have made,
|
||||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
where such license applies only to those patent claims licensable
|
where such license applies only to those patent claims licensable
|
||||||
by such Contributor that are necessarily infringed by their
|
by such Contributor that are necessarily infringed by their
|
||||||
Contribution(s) alone or by combination of their Contribution(s)
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
with the Work to which such Contribution(s) was submitted. If You
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
institute patent litigation against any entity (including a
|
institute patent litigation against any entity (including a
|
||||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
or a Contribution incorporated within the Work constitutes direct
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
or contributory patent infringement, then any patent licenses
|
or contributory patent infringement, then any patent licenses
|
||||||
granted to You under this License for that Work shall terminate
|
granted to You under this License for that Work shall terminate
|
||||||
as of the date such litigation is filed.
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
Work or Derivative Works thereof in any medium, with or without
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
modifications, and in Source or Object form, provided that You
|
modifications, and in Source or Object form, provided that You
|
||||||
meet the following conditions:
|
meet the following conditions:
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or
|
(a) You must give any other recipients of the Work or
|
||||||
Derivative Works a copy of this License; and
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices
|
(b) You must cause any modified files to carry prominent notices
|
||||||
stating that You changed the files; and
|
stating that You changed the files; and
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
that You distribute, all copyright, patent, trademark, and
|
that You distribute, all copyright, patent, trademark, and
|
||||||
attribution notices from the Source form of the Work,
|
attribution notices from the Source form of the Work,
|
||||||
excluding those notices that do not pertain to any part of
|
excluding those notices that do not pertain to any part of
|
||||||
the Derivative Works; and
|
the Derivative Works; and
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
distribution, then any Derivative Works that You distribute must
|
distribution, then any Derivative Works that You distribute must
|
||||||
include a readable copy of the attribution notices contained
|
include a readable copy of the attribution notices contained
|
||||||
within such NOTICE file, excluding those notices that do not
|
within such NOTICE file, excluding those notices that do not
|
||||||
pertain to any part of the Derivative Works, in at least one
|
pertain to any part of the Derivative Works, in at least one
|
||||||
of the following places: within a NOTICE text file distributed
|
of the following places: within a NOTICE text file distributed
|
||||||
as part of the Derivative Works; within the Source form or
|
as part of the Derivative Works; within the Source form or
|
||||||
documentation, if provided along with the Derivative Works; or,
|
documentation, if provided along with the Derivative Works; or,
|
||||||
within a display generated by the Derivative Works, if and
|
within a display generated by the Derivative Works, if and
|
||||||
wherever such third-party notices normally appear. The contents
|
wherever such third-party notices normally appear. The contents
|
||||||
of the NOTICE file are for informational purposes only and
|
of the NOTICE file are for informational purposes only and
|
||||||
do not modify the License. You may add Your own attribution
|
do not modify the License. You may add Your own attribution
|
||||||
notices within Derivative Works that You distribute, alongside
|
notices within Derivative Works that You distribute, alongside
|
||||||
or as an addendum to the NOTICE text from the Work, provided
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
that such additional attribution notices cannot be construed
|
that such additional attribution notices cannot be construed
|
||||||
as modifying the License.
|
as modifying the License.
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and
|
You may add Your own copyright statement to Your modifications and
|
||||||
may provide additional or different license terms and conditions
|
may provide additional or different license terms and conditions
|
||||||
for use, reproduction, or distribution of Your modifications, or
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
for any such Derivative Works as a whole, provided Your use,
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
reproduction, and distribution of the Work otherwise complies with
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
the conditions stated in this License.
|
the conditions stated in this License.
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
any Contribution intentionally submitted for inclusion in the Work
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
by You to the Licensor shall be under the terms and conditions of
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
this License, without any additional terms or conditions.
|
this License, without any additional terms or conditions.
|
||||||
Notwithstanding the above, nothing herein shall supersede or modify
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
the terms of any separate license agreement you may have executed
|
the terms of any separate license agreement you may have executed
|
||||||
with Licensor regarding such Contributions.
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
names, trademarks, service marks, or product names of the Licensor,
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
except as required for reasonable and customary use in describing the
|
except as required for reasonable and customary use in describing the
|
||||||
origin of the Work and reproducing the content of the NOTICE file.
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
agreed to in writing, Licensor provides the Work (and each
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
implied, including, without limitation, any warranties or conditions
|
implied, including, without limitation, any warranties or conditions
|
||||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
appropriateness of using or redistributing the Work and assume any
|
appropriateness of using or redistributing the Work and assume any
|
||||||
risks associated with Your exercise of permissions under this License.
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory,
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
whether in tort (including negligence), contract, or otherwise,
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
unless required by applicable law (such as deliberate and grossly
|
unless required by applicable law (such as deliberate and grossly
|
||||||
negligent acts) or agreed to in writing, shall any Contributor be
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
liable to You for damages, including any direct, indirect, special,
|
liable to You for damages, including any direct, indirect, special,
|
||||||
incidental, or consequential damages of any character arising as a
|
incidental, or consequential damages of any character arising as a
|
||||||
result of this License or out of the use or inability to use the
|
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 (including but not limited to damages for loss of goodwill,
|
||||||
work stoppage, computer failure or malfunction, or any and all
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
other commercial damages or losses), even if such Contributor
|
other commercial damages or losses), even if such Contributor
|
||||||
has been advised of the possibility of such damages.
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
the Work or Derivative Works thereof, You may choose to offer,
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
or other liability obligations and/or rights consistent with this
|
or other liability obligations and/or rights consistent with this
|
||||||
License. However, in accepting such obligations, You may act only
|
License. However, in accepting such obligations, You may act only
|
||||||
on Your own behalf and on Your sole responsibility, not on behalf
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
of any other Contributor, and only if You agree to indemnify,
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
defend, and hold each Contributor harmless for any liability
|
defend, and hold each Contributor harmless for any liability
|
||||||
incurred by, or claims asserted against, such Contributor by reason
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
of your accepting any such warranty or additional liability.
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
APPENDIX: How to apply the Apache License to your work.
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
To apply the Apache License to your work, attach the following
|
To apply the Apache License to your work, attach the following
|
||||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
replaced with your own identifying information. (Don't include
|
replaced with your own identifying information. (Don't include
|
||||||
the brackets!) The text should be enclosed in the appropriate
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
comment syntax for the file format. We also recommend that a
|
comment syntax for the file format. We also recommend that a
|
||||||
file or class name and description of purpose be included on the
|
file or class name and description of purpose be included on the
|
||||||
same "printed page" as the copyright notice for easier
|
same "printed page" as the copyright notice for easier
|
||||||
identification within third-party archives.
|
identification within third-party archives.
|
||||||
|
|
||||||
Copyright [yyyy] [name of copyright owner]
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
You may obtain a copy of the License at
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
Unless required by applicable law or agreed to in writing, software
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
See the License for the specific language governing permissions and
|
See the License for the specific language governing permissions and
|
||||||
limitations under the License.
|
limitations under the License.
|
||||||
|
|||||||
+185
@@ -0,0 +1,185 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
|
class LotteryDraw
|
||||||
|
{
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $goods
|
||||||
|
* @param string $wight
|
||||||
|
* @return mixed
|
||||||
|
* @uses $reward = Lucked::luck($data);
|
||||||
|
*/
|
||||||
|
public static function luck(array $goods, string $wight = 'probability'): mixed
|
||||||
|
{
|
||||||
|
static $class = null;
|
||||||
|
if ($class === null) $class = new LotteryDraw();
|
||||||
|
|
||||||
|
if (count($goods) < 1) return null;
|
||||||
|
|
||||||
|
$prob = $alias = [];
|
||||||
|
|
||||||
|
$class->ket($array = $class->init($goods, $wight), $prob, $alias);
|
||||||
|
|
||||||
|
$result = $class->generation($array, $prob, $alias);
|
||||||
|
if (!isset($goods[$result])) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return $goods[$result];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $goods
|
||||||
|
* @param string $wight
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
protected function init(array $goods, string $wight): array
|
||||||
|
{
|
||||||
|
$defaultIndex = -1;
|
||||||
|
|
||||||
|
$array = [];
|
||||||
|
foreach ($goods as $key => $val) {
|
||||||
|
if ($val[$wight] == 0) $defaultIndex = $key;
|
||||||
|
$array[] = (float)$val[$wight];
|
||||||
|
}
|
||||||
|
|
||||||
|
$total = array_sum($array);
|
||||||
|
if ($total > 1) {
|
||||||
|
$array = $this->reset($array, $total);
|
||||||
|
$total = array_sum($array);
|
||||||
|
}
|
||||||
|
if (1 - $total !== floatval(0)) {
|
||||||
|
if ($defaultIndex == -1) {
|
||||||
|
$defaultIndex = count($goods);
|
||||||
|
}
|
||||||
|
$array[$defaultIndex] = 1 - array_sum($array);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $array;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $data
|
||||||
|
* @param float $total
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
protected function reset(array $data, float $total): array
|
||||||
|
{
|
||||||
|
$length = $this->getMin($data);
|
||||||
|
foreach ($data as $key => $val) {
|
||||||
|
$data[$key] = ($val * $length - ($val * $length) / ($total * $length)) / $length;
|
||||||
|
}
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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 = mt_rand(1, $MAX_P) / $MAX_P; // 抛出硬币
|
||||||
|
|
||||||
|
$col = mt_rand(0, $nums); // 随机落在一列
|
||||||
|
$b_head = $coin_toss > $prob[$col]; // 判断是否落在原色
|
||||||
|
|
||||||
|
return $b_head ? $alias[$col] : $col;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param $num
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
private function getMin($num): int
|
||||||
|
{
|
||||||
|
$length = $this->getFloatLength($this->mini($num));
|
||||||
|
|
||||||
|
return (int)sprintf('1%0' . $length . 'd', 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param $num
|
||||||
|
* @return int|float
|
||||||
|
*/
|
||||||
|
protected function mini($num): int|float
|
||||||
|
{
|
||||||
|
$def = current($num);
|
||||||
|
foreach ($num as $val) {
|
||||||
|
if ($val < $def) {
|
||||||
|
$def = $val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $def;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param $float
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
private function getFloatLength($float): int
|
||||||
|
{
|
||||||
|
$ex = explode('.', $float);
|
||||||
|
|
||||||
|
return strlen(end($ex));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $data
|
||||||
|
* @param array $prob
|
||||||
|
* @param array $alias
|
||||||
|
*/
|
||||||
|
private function ket(array $data, array &$prob, array &$alias): void
|
||||||
|
{
|
||||||
|
$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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
-151
@@ -1,151 +0,0 @@
|
|||||||
<?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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
+12
-12
@@ -1,12 +1,12 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
interface OnJsonRpcInterface
|
interface OnJsonRpcInterface
|
||||||
{
|
{
|
||||||
|
|
||||||
|
|
||||||
// public function execute();
|
// public function execute();
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
interface OnRpcConsumerInterface
|
interface OnRpcConsumerInterface
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
|
||||||
|
|
||||||
use Psr\Http\Client\ClientInterface;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @mixin JsonRpcTransporter
|
|
||||||
*/
|
|
||||||
interface RpcClientInterface extends ClientInterface
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
+254
-274
@@ -1,274 +1,254 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
use Http\Constrict\RequestInterface;
|
use Exception;
|
||||||
use Http\Handler\Handler;
|
use JetBrains\PhpStorm\ArrayShape;
|
||||||
use Http\Handler\Router;
|
use Kiri;
|
||||||
use Http\Message\ServerRequest;
|
use Kiri\Abstracts\Component;
|
||||||
use Kiri\Abstracts\Component;
|
use Kiri\Core\Json;
|
||||||
use Kiri\Abstracts\Config;
|
use Kiri\Events\EventProvider;
|
||||||
use Kiri\Consul\Agent;
|
use Kiri\Server\Contract\OnCloseInterface;
|
||||||
use Kiri\Context;
|
use Kiri\Server\Contract\OnConnectInterface;
|
||||||
use Kiri\Events\EventProvider;
|
use Kiri\Server\Contract\OnReceiveInterface;
|
||||||
use Kiri\Exception\ConfigException;
|
use Kiri\Server\Events\OnBeforeShutdown;
|
||||||
use Kiri\Kiri;
|
use Kiri\Server\Events\OnServerBeforeStart;
|
||||||
use Kiri\Annotation\Inject;
|
use Psr\Container\ContainerExceptionInterface;
|
||||||
use Kiri\Annotation\Annotation;
|
use Psr\Container\NotFoundExceptionInterface;
|
||||||
use Psr\Container\ContainerExceptionInterface;
|
use ReflectionException;
|
||||||
use Psr\Container\NotFoundExceptionInterface;
|
use Swoole\Coroutine;
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
use Kiri\Router\RouterCollector;
|
||||||
use ReflectionException;
|
use Psr\Container\ContainerInterface;
|
||||||
use Server\Contract\OnCloseInterface;
|
use Swoole\Coroutine\Channel;
|
||||||
use Server\Contract\OnConnectInterface;
|
use Swoole\Server;
|
||||||
use Server\Contract\OnReceiveInterface;
|
use Kiri\Router\DataGrip;
|
||||||
use Server\Events\OnBeforeShutdown;
|
|
||||||
use Server\Events\OnServerBeforeStart;
|
/**
|
||||||
use Server\Events\OnTaskerStart;
|
*
|
||||||
use Server\Events\OnWorkerStart;
|
*/
|
||||||
use Swoole\Coroutine;
|
class RpcJsonp extends Component implements OnConnectInterface, OnReceiveInterface, OnCloseInterface
|
||||||
use Swoole\Coroutine\Channel;
|
{
|
||||||
use Swoole\Server;
|
|
||||||
use Swoole\Timer;
|
|
||||||
|
public RouterCollector $collector;
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
/**
|
||||||
*/
|
* @param ContainerInterface $container
|
||||||
class RpcJsonp extends Component implements OnConnectInterface, OnReceiveInterface, OnCloseInterface
|
* @param DataGrip $dataGrip
|
||||||
{
|
* @param RpcManager $manager
|
||||||
|
* @param EventProvider $eventProvider
|
||||||
|
* @throws Exception
|
||||||
#[Inject(Router::class)]
|
*/
|
||||||
public Router $router;
|
public function __construct(public ContainerInterface $container,
|
||||||
|
public DataGrip $dataGrip,
|
||||||
|
public RpcManager $manager,
|
||||||
#[Inject(Annotation::class)]
|
public EventProvider $eventProvider)
|
||||||
public Annotation $annotation;
|
{
|
||||||
|
parent::__construct();
|
||||||
|
}
|
||||||
|
|
||||||
private RpcManager $manager;
|
|
||||||
|
/**
|
||||||
/**
|
* @return void
|
||||||
*
|
* @throws ContainerExceptionInterface
|
||||||
* @throws \Exception
|
* @throws NotFoundExceptionInterface
|
||||||
*/
|
* @throws ReflectionException
|
||||||
public function init(): void
|
* @throws Exception
|
||||||
{
|
*/
|
||||||
$this->eventProvider->on(OnBeforeShutdown::class, [$this, 'onBeforeShutdown']);
|
public function init(): void
|
||||||
|
{
|
||||||
scan_directory(APP_PATH . 'rpc', 'Rpc');
|
$this->eventProvider->on(OnBeforeShutdown::class, [$this, 'onBeforeShutdown']);
|
||||||
|
|
||||||
$this->eventProvider->on(OnWorkerStart::class, [$this, 'consulWatches']);
|
$this->collector = $this->dataGrip->get('rpc');
|
||||||
$this->eventProvider->on(OnServerBeforeStart::class, [$this, 'register']);
|
}
|
||||||
|
|
||||||
$this->manager = Kiri::getDi()->get(RpcManager::class);
|
|
||||||
}
|
/**
|
||||||
|
* @param OnBeforeShutdown $beforeShutdown
|
||||||
|
* @return void
|
||||||
/**
|
*/
|
||||||
* @param OnBeforeShutdown $beforeShutdown
|
public function onBeforeShutdown(OnBeforeShutdown $beforeShutdown): void
|
||||||
* @return void
|
{
|
||||||
* @throws ContainerExceptionInterface
|
if (env('environmental') != Kiri::WORKER && env('environmental_workerId') != 0) {
|
||||||
* @throws NotFoundExceptionInterface
|
return;
|
||||||
*/
|
}
|
||||||
public function onBeforeShutdown(OnBeforeShutdown $beforeShutdown)
|
|
||||||
{
|
}
|
||||||
$doneList = $this->manager->doneList();
|
|
||||||
$agent = $this->container->get(Agent::class);
|
|
||||||
foreach ($doneList as $value) {
|
/**
|
||||||
$agent->service->deregister($value['config']['ID']);
|
* @param OnServerBeforeStart $server
|
||||||
$agent->checks->deregister($value['config']['Check']['CheckId']);
|
*/
|
||||||
}
|
public function register(OnServerBeforeStart $server)
|
||||||
}
|
{
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param OnWorkerStart|OnTaskerStart $server
|
/**
|
||||||
* @throws ConfigException
|
* @param Server $server
|
||||||
*/
|
* @param int $fd
|
||||||
public function consulWatches(OnWorkerStart|OnTaskerStart $server)
|
*/
|
||||||
{
|
public function onConnect(Server $server, int $fd): void
|
||||||
if ($server->workerId != 0) {
|
{
|
||||||
return;
|
// TODO: Implement onConnect() method.
|
||||||
}
|
}
|
||||||
$async_time = (int)Config::get('consul.async_time', 1000);
|
|
||||||
Timer::tick($async_time, static function ($timeId) {
|
|
||||||
if (env('state', 'start') == 'exit') {
|
/**
|
||||||
Timer::clear($timeId);
|
* @param Server $server
|
||||||
return;
|
* @param int $fd
|
||||||
}
|
* @param int $reactor_id
|
||||||
Kiri::getDi()->get(RpcManager::class)->tick();
|
* @param string $data
|
||||||
});
|
* @return bool
|
||||||
}
|
*/
|
||||||
|
public function onReceive(Server $server, int $fd, int $reactor_id, string $data): bool
|
||||||
|
{
|
||||||
/**
|
try {
|
||||||
* @param OnServerBeforeStart $server
|
$data = json_decode($data, true);
|
||||||
*/
|
if (is_null($data)) return $server->send($fd, 'success', $reactor_id);
|
||||||
public function register(OnServerBeforeStart $server)
|
$data = json_decode($data, true);
|
||||||
{
|
if (!is_array($data)) {
|
||||||
$this->manager->register();
|
throw new Exception('Parse error语法解析错误', -32700);
|
||||||
}
|
}
|
||||||
|
if (!isset($data['jsonrpc']) || !isset($data['method']) || $data['jsonrpc'] != '2.0') {
|
||||||
|
throw new Exception('Invalid Request无效请求', -32600);
|
||||||
/**
|
}
|
||||||
* @param Server $server
|
return $server->send($fd, $this->batchDispatch($data), $reactor_id);
|
||||||
* @param int $fd
|
} catch (\Throwable $throwable) {
|
||||||
*/
|
$response = Json::encode($this->failure(-32700, $throwable->getMessage()));
|
||||||
public function onConnect(Server $server, int $fd): void
|
|
||||||
{
|
$this->getLogger()->json_log($throwable);
|
||||||
// TODO: Implement onConnect() method.
|
|
||||||
}
|
return $server->send($fd, $response, $reactor_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
/**
|
|
||||||
* @param Server $server
|
|
||||||
* @param int $fd
|
/**
|
||||||
* @param int $reactor_id
|
* @param array $data
|
||||||
* @param string $data
|
* @return string|bool
|
||||||
*/
|
*/
|
||||||
public function onReceive(Server $server, int $fd, int $reactor_id, string $data): void
|
private function batchDispatch(array $data): string|bool
|
||||||
{
|
{
|
||||||
$data = json_decode($data, true);
|
if (isset($data['jsonrpc'])) {
|
||||||
if (is_null($data)) {
|
$result = $this->dispatch($data);
|
||||||
$this->failure(-32700, 'Parse error语法解析错误');
|
if (!isset($data['id'])) {
|
||||||
} else if (!isset($data['jsonrpc']) || !isset($data['method']) || $data['jsonrpc'] != '2.0') {
|
$result = [1];
|
||||||
$this->failure(-32600, 'Invalid Request无效请求');
|
}
|
||||||
} else {
|
} else {
|
||||||
$this->batchDispatch($server, $fd, $data);
|
$channel = new Channel($total = count($data));
|
||||||
}
|
foreach ($data as $datum) {
|
||||||
}
|
$this->_execute($channel, $datum);
|
||||||
|
}
|
||||||
|
$result = [];
|
||||||
/**
|
for ($i = 0; $i < $total; $i++) {
|
||||||
* @param Server $server
|
$result[] = $channel->pop();
|
||||||
* @param int $fd
|
}
|
||||||
* @param array $data
|
}
|
||||||
* @return void
|
return json_encode($result, JSON_UNESCAPED_UNICODE);
|
||||||
*/
|
}
|
||||||
private function batchDispatch(Server $server, int $fd, array $data): void
|
|
||||||
{
|
|
||||||
if (isset($data['jsonrpc'])) {
|
/**
|
||||||
$dispatch = $this->dispatch($data);
|
* @param $channel
|
||||||
if (!isset($data['id'])) {
|
* @param $datum
|
||||||
$dispatch = [1];
|
*/
|
||||||
}
|
private function _execute($channel, $datum)
|
||||||
$result = json_encode($dispatch, JSON_UNESCAPED_UNICODE);
|
{
|
||||||
} else {
|
Coroutine::create(function () use ($channel, $datum) {
|
||||||
$channel = new Channel($total = count($data));
|
if (empty($datum) || !isset($datum['jsonrpc'])) {
|
||||||
foreach ($data as $datum) {
|
$channel->push($this->failure(-32700, 'Parse error语法解析错误'));
|
||||||
$this->_execute($channel, $datum);
|
} else if (!isset($datum['method'])) {
|
||||||
}
|
$channel->push($this->failure(-32700, 'Parse error语法解析错误'));
|
||||||
$result = [];
|
} else {
|
||||||
for ($i = 0; $i < $total; $i++) {
|
$dispatch = $this->dispatch($datum);
|
||||||
$result[] = $channel->pop();
|
if (!isset($dispatch['id'])) {
|
||||||
}
|
$dispatch = [1];
|
||||||
}
|
}
|
||||||
$server->send($fd, json_encode($result, JSON_UNESCAPED_UNICODE));
|
$channel->push($dispatch);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
/**
|
|
||||||
* @param $channel
|
|
||||||
* @param $datum
|
/**
|
||||||
*/
|
* @param $data
|
||||||
private function _execute($channel, $datum)
|
* @return array
|
||||||
{
|
*/
|
||||||
Coroutine::create(function () use ($channel, $datum) {
|
private function dispatch($data): array
|
||||||
if (empty($datum) || !isset($datum['jsonrpc'])) {
|
{
|
||||||
$channel->push($this->failure(-32700, 'Parse error语法解析错误'));
|
// try {
|
||||||
} else if (!isset($datum['method'])) {
|
// $class = $this->collector->query($data['service'], 'tcp');
|
||||||
$channel->push($this->failure(-32700, 'Parse error语法解析错误'));
|
// if (!$this->container->has($class)) {
|
||||||
} else {
|
// throw new Exception('Handler not found', -32601);
|
||||||
$dispatch = $this->dispatch($datum);
|
// }
|
||||||
if (!isset($dispatch['id'])) {
|
// $controller = $this->container->get($class);
|
||||||
$dispatch = [1];
|
// if (!method_exists($controller, $data['method'])) {
|
||||||
}
|
// throw new Exception('Method not found', -32601);
|
||||||
$channel->push($dispatch);
|
// }
|
||||||
}
|
// if (!isset($data['params']) || !is_array($data['params'])) {
|
||||||
});
|
// $data['params'] = [];
|
||||||
}
|
// }
|
||||||
|
// return $this->handler($controller, $data['method'], $data['params']);
|
||||||
|
// } catch (\Throwable $throwable) {
|
||||||
/**
|
// $code = $throwable->getCode() == 0 ? -32603 : $throwable->getCode();
|
||||||
* @param $data
|
// return $this->failure($code, jTraceEx($throwable), [], $data['id'] ?? null);
|
||||||
* @return array
|
// }
|
||||||
*/
|
return $this->failure(404, 'Not found.');
|
||||||
private function dispatch($data): array
|
}
|
||||||
{
|
|
||||||
try {
|
|
||||||
[$handler, $params] = $this->container->get(RpcManager::class)->get($data['service'], $data['method']);
|
/**
|
||||||
if (is_null($handler)) {
|
* @param $controller
|
||||||
throw new \Exception('Method not found', -32601);
|
* @param string $method
|
||||||
} else {
|
* @param $params
|
||||||
Context::setContext(RequestInterface::class, $this->createServerRequest($params));
|
* @return array
|
||||||
|
*/
|
||||||
return $this->handler($handler);
|
#[ArrayShape([])]
|
||||||
}
|
private function handler($controller, string $method, $params): array
|
||||||
} catch (\Throwable $throwable) {
|
{
|
||||||
$code = $throwable->getCode() == 0 ? -32603 : $throwable->getCode();
|
$result = call_user_func([$controller, $method], ...$params);
|
||||||
return $this->failure($code, jTraceEx($throwable), [], $data['id'] ?? null);
|
return [
|
||||||
}
|
'jsonrpc' => '2.0',
|
||||||
}
|
'result' => $result,
|
||||||
|
'id' => $data['id'] ?? null
|
||||||
|
];
|
||||||
/**
|
}
|
||||||
* @param $params
|
|
||||||
* @return ServerRequestInterface
|
|
||||||
* @throws \Exception
|
/**
|
||||||
*/
|
* @param $code
|
||||||
private function createServerRequest($params): ServerRequestInterface
|
* @param $message
|
||||||
{
|
* @param array $data
|
||||||
return (new ServerRequest())->withParsedBody($params);
|
* @param null $id
|
||||||
}
|
* @return array
|
||||||
|
*/
|
||||||
|
#[ArrayShape([])]
|
||||||
/**
|
protected function failure($code, $message, array $data = [], $id = null): array
|
||||||
* @param Handler $handler
|
{
|
||||||
* @return array
|
$error = [
|
||||||
*/
|
'jsonrpc' => '2.0',
|
||||||
private function handler(Handler $handler): array
|
'error' => [
|
||||||
{
|
'code' => $code,
|
||||||
return [
|
'message' => $message,
|
||||||
'jsonrpc' => '2.0',
|
'data' => $data
|
||||||
'result' => call_user_func($handler->callback, ...$handler->params),
|
]
|
||||||
'id' => $data['id'] ?? null
|
];
|
||||||
];
|
if (!is_null($id)) {
|
||||||
}
|
$error['id'] = $id;
|
||||||
|
}
|
||||||
|
return $error;
|
||||||
/**
|
}
|
||||||
* @param $code
|
|
||||||
* @param $message
|
|
||||||
* @param array $data
|
/**
|
||||||
* @param null $id
|
* @param Server $server
|
||||||
* @return array
|
* @param int $fd
|
||||||
*/
|
* @return void
|
||||||
protected function failure($code, $message, array $data = [], $id = null): array
|
*/
|
||||||
{
|
public function OnClose(Server $server, int $fd): void
|
||||||
$error = [
|
{
|
||||||
'jsonrpc' => '2.0',
|
// TODO: Implement onClose() method.
|
||||||
'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.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+39
-138
@@ -1,138 +1,39 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
use Http\Handler\Handler;
|
use Etcd\Client;
|
||||||
use Kiri\Abstracts\Component;
|
use Kiri;
|
||||||
use Kiri\Consul\Agent;
|
use Kiri\Abstracts\Component;
|
||||||
use Kiri\Consul\Health;
|
use PhpParser\Node\Stmt\Return_;
|
||||||
use Kiri\Kiri;
|
|
||||||
use ReflectionException;
|
|
||||||
|
/**
|
||||||
class RpcManager extends Component
|
* class RpcManager
|
||||||
{
|
*/
|
||||||
|
class RpcManager extends Component
|
||||||
|
{
|
||||||
/**
|
|
||||||
* @var array
|
|
||||||
*/
|
protected array $services = [];
|
||||||
private array $_rpc = [];
|
|
||||||
|
|
||||||
|
/**
|
||||||
/**
|
* @return void
|
||||||
* @param $serviceName
|
*/
|
||||||
* @return void
|
public function watch(): void
|
||||||
* @throws ReflectionException
|
{
|
||||||
* @throws \Exception
|
$data = new Client('','');
|
||||||
*/
|
}
|
||||||
public function async($serviceName): void
|
|
||||||
{
|
|
||||||
$lists = Kiri::getDi()->get(Health::class)->setQuery('passing=true')->service($serviceName);
|
/**
|
||||||
if ($lists->getStatusCode() != 200) {
|
* @param $service
|
||||||
return;
|
* @return mixed
|
||||||
}
|
*/
|
||||||
$body = json_decode($lists->getBody(), true);
|
public function getServices($service): mixed
|
||||||
$file = storage('.rpc.clients.' . md5($serviceName), 'rpc');
|
{
|
||||||
if (!empty($body) && is_array($body)) {
|
return $this->services[$service] ?? null;
|
||||||
file_put_contents($file, json_encode(array_column($body, 'Service')), LOCK_EX);
|
}
|
||||||
} else {
|
|
||||||
file_put_contents($file, json_encode([]), LOCK_EX);
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @throws ReflectionException
|
|
||||||
*/
|
|
||||||
public function tick(): void
|
|
||||||
{
|
|
||||||
foreach ($this->_rpc as $name => $list) {
|
|
||||||
$this->async($name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @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) {
|
|
||||||
$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];
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
|
use Kiri\Di\Context;
|
||||||
|
use Kiri\Server\Processes\AbstractProcess;
|
||||||
|
use Swoole\Coroutine;
|
||||||
|
use Swoole\Process;
|
||||||
|
use function pcntl_signal;
|
||||||
|
|
||||||
|
class RpcProcess extends AbstractProcess
|
||||||
|
{
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getName(): string
|
||||||
|
{
|
||||||
|
return "Rpc Manager";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Process|null $process
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function process(?Process $process): void
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function onSigterm(): void
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
class RpcServiceException extends \Exception
|
class RpcServiceException extends \Exception
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Kiri\Rpc\AbstractRpcClient;
|
||||||
|
|
||||||
|
|
||||||
|
class TestRpc extends AbstractRpcClient
|
||||||
|
{
|
||||||
|
|
||||||
|
public string $service = '';
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param $data
|
||||||
|
* @param $nba
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public function test($data, $nba): mixed
|
||||||
|
{
|
||||||
|
$resp = $this->send(__FUNCTION__, $data, $nba);
|
||||||
|
|
||||||
|
return json_decode($resp, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
+103
-78
@@ -1,78 +1,103 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Kiri\Rpc;
|
namespace Kiri\Rpc;
|
||||||
|
|
||||||
use Exception;
|
use Exception;
|
||||||
use Kiri\Context;
|
use JetBrains\PhpStorm\ArrayShape;
|
||||||
use Swoole\Client;
|
use Kiri\Di\Context;
|
||||||
use Swoole\Coroutine;
|
use Kiri\Di\Inject\Container;
|
||||||
|
use Swoole\Client;
|
||||||
trait TraitTransporter
|
use Swoole\Coroutine;
|
||||||
{
|
|
||||||
|
trait TraitTransporter
|
||||||
|
{
|
||||||
protected array $config;
|
|
||||||
|
|
||||||
|
/**
|
||||||
protected array $clients = [];
|
* @var RpcManager
|
||||||
|
*/
|
||||||
|
#[Container(RpcManager::class)]
|
||||||
/**
|
public RpcManager $manager;
|
||||||
* @param $config
|
|
||||||
* @return $this
|
|
||||||
*/
|
protected array $config;
|
||||||
public function withConfig($config): static
|
|
||||||
{
|
|
||||||
$this->config = $config;
|
/**
|
||||||
return $this;
|
* @param resource $client
|
||||||
}
|
* @param $content
|
||||||
|
* @return string|bool
|
||||||
|
*/
|
||||||
/**
|
protected function request(mixed $client, $content): string|bool
|
||||||
* @param Client|Coroutine\Client $client
|
{
|
||||||
* @param $content
|
socket_write($client, \msgpack_pack($content), mb_strlen($content));
|
||||||
* @param bool $isClose
|
|
||||||
* @return mixed
|
socket_read($client, 1024);
|
||||||
*/
|
|
||||||
private function request(Client|Coroutine\Client $client, $content, bool $isClose): mixed
|
return \msgpack_unpack($client->recv());
|
||||||
{
|
}
|
||||||
$client->send($content);
|
|
||||||
$read = $client->recv();
|
|
||||||
if ($isClose) {
|
/**
|
||||||
$client->close();
|
* @param string $service
|
||||||
}
|
* @return $this
|
||||||
return $read;
|
* @throws RpcServiceException
|
||||||
}
|
*/
|
||||||
|
protected function get_consul(string $service): static
|
||||||
|
{
|
||||||
/**
|
if (empty($service)) {
|
||||||
* @return Client|Coroutine\Client
|
throw new RpcServiceException('You need set rpc service name if used.');
|
||||||
* @throws Exception
|
}
|
||||||
*/
|
$sf = $this->manager->getServices($service);
|
||||||
private function newClient(): Coroutine\Client|Client
|
if (empty($sf) || !is_array($sf)) {
|
||||||
{
|
throw new RpcServiceException('You need set rpc service name if used.');
|
||||||
$alias = $this->alias($this->config);
|
}
|
||||||
$client = $this->clients[$alias] ?? null;
|
$this->config = $this->_loadRand($sf);
|
||||||
if (is_null($client)) {
|
return $this;
|
||||||
$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)) {
|
* @param $services
|
||||||
throw new Exception('connect fail.');
|
* @return array
|
||||||
}
|
*/
|
||||||
return $client;
|
#[ArrayShape(['Address' => "mixed", 'Port' => "mixed"])]
|
||||||
}
|
protected function _loadRand($services): array
|
||||||
|
{
|
||||||
|
$array = [];
|
||||||
/**
|
foreach ($services as $value) {
|
||||||
* @param array $config
|
$value['Weight'] = $value['Weights']['Passing'];
|
||||||
* @return string
|
$array[] = $value;
|
||||||
*/
|
}
|
||||||
private function alias(array $config): string
|
if (count($array) < 2) {
|
||||||
{
|
$luck = $array[0];
|
||||||
return $config['Address'] . '::' . $config['Port'];
|
} else {
|
||||||
}
|
$luck = LotteryDraw::luck($array, 'Weight');
|
||||||
|
}
|
||||||
|
return [
|
||||||
}
|
'Address' => $luck['TaggedAddresses']['wan_ipv4']['Address'],
|
||||||
|
'Port' => $luck['TaggedAddresses']['wan_ipv4']['Port']
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return Client|Coroutine\Client
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
protected function newClient(): Coroutine\Client|Client
|
||||||
|
{
|
||||||
|
if (Context::inCoroutine()) {
|
||||||
|
$client = new Coroutine\Client(SWOOLE_SOCK_TCP);
|
||||||
|
} else {
|
||||||
|
$client = new Client(SWOOLE_SOCK_TCP);
|
||||||
|
}
|
||||||
|
[$host, $port] = [$this->config['Address'], $this->config['Port']];
|
||||||
|
if (!$client->isConnected() && !$client->connect($host, $port, 60)) {
|
||||||
|
throw new Exception('connect fail.');
|
||||||
|
}
|
||||||
|
return $client;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
+33
-24
@@ -1,24 +1,33 @@
|
|||||||
{
|
{
|
||||||
"name": "game-worker/kiri-rpc",
|
"name": "game-worker/kiri-rpc",
|
||||||
"description": "kiri-rpc",
|
"description": "kiri-rpc",
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "XiangLin",
|
"name": "XiangLin",
|
||||||
"email": "as2252258@163.com"
|
"email": "as2252258@163.com"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"require": {
|
"require": {
|
||||||
"php": ">=8.0",
|
"php": ">=8.5",
|
||||||
"ext-json": "*",
|
"ext-json": "*",
|
||||||
"psr/http-client": "^1.0",
|
"ext-msgpack": "*",
|
||||||
"psr/http-message": "^1.0"
|
"start-point/etcd-php": "^1.1",
|
||||||
},
|
"game-worker/kiri-pool": "^v1.0",
|
||||||
"autoload": {
|
"linkorb/etcd-php": "^1.6"
|
||||||
"psr-4": {
|
},
|
||||||
"Kiri\\Rpc\\": "./"
|
"replace": {
|
||||||
}
|
"symfony/polyfill-apcu": "*",
|
||||||
},
|
"symfony/polyfill-php80": "*",
|
||||||
"require-dev": {
|
"symfony/polyfill-mbstring": "*",
|
||||||
}
|
"symfony/polyfill-ctype": "*",
|
||||||
}
|
"symfony/polyfill-php73": "*",
|
||||||
|
"symfony/polyfill-php72": "*",
|
||||||
|
"symfony/polyfill-php81": "*"
|
||||||
|
},
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"Kiri\\Rpc\\": "./"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+67
-77
@@ -1,77 +1,67 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
|
||||||
use Kiri\Rpc\RpcJsonp;
|
use Kiri\Rpc\RpcJsonp;
|
||||||
use Kiri\Rpc\TestRpcService;
|
use Kiri\Rpc\TestRpcService;
|
||||||
use Server\Constant;
|
use Kiri\Server\Constant;
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'rpc' => [
|
'rpc' => [
|
||||||
'name' => 'json-rpc',
|
'name' => 'json-rpc',
|
||||||
'type' => Constant::SERVER_TYPE_BASE,
|
'type' => Constant::SERVER_TYPE_BASE,
|
||||||
'mode' => SWOOLE_SOCK_TCP,
|
'mode' => SWOOLE_SOCK_TCP,
|
||||||
'host' => '0.0.0.0',
|
'host' => '0.0.0.0',
|
||||||
'port' => 9526,
|
'port' => 9526,
|
||||||
'settings' => [
|
'settings' => [
|
||||||
|
|
||||||
],
|
],
|
||||||
'events' => [
|
'events' => [
|
||||||
Constant::RECEIVE => [RpcJsonp::class, 'onReceive']
|
Constant::RECEIVE => [RpcJsonp::class, 'onReceive']
|
||||||
],
|
]
|
||||||
|
],
|
||||||
|
|
||||||
'consumers' => [
|
|
||||||
'class' => TestRpcService::class,
|
'service' => [
|
||||||
'name' => 'test-rpc',
|
[
|
||||||
'package' => 'test',
|
"datacenter" => "dc1",
|
||||||
'register' => [
|
"id" => "40e4a748-2192-161a-0510-9bf59fe950b5",
|
||||||
'host' => '',
|
"node" => "FriendRpcService",
|
||||||
'port' => ''
|
'class' => TestRpc::class,
|
||||||
]
|
"skipNodeUpdate" => false,
|
||||||
]
|
"service" => [
|
||||||
],
|
"id" => "redis1",
|
||||||
|
"service" => "FriendRpcService",
|
||||||
|
"address" => "172.26.221.211",
|
||||||
'service' => [
|
"taggedAddresses" => [
|
||||||
[
|
"lan" => [
|
||||||
"datacenter" => "dc1",
|
"address" => "127.0.0.1",
|
||||||
"id" => "40e4a748-2192-161a-0510-9bf59fe950b5",
|
"port" => 8000
|
||||||
"node" => "FriendRpcService",
|
],
|
||||||
"skipNodeUpdate" => false,
|
"wan" => [
|
||||||
"service" => [
|
"address" => "172.26.221.211",
|
||||||
"id" => "redis1",
|
"port" => 80
|
||||||
"service" => "FriendRpcService",
|
]
|
||||||
"address" => "172.26.221.211",
|
],
|
||||||
"taggedAddresses" => [
|
"meta" => [
|
||||||
"lan" => [
|
"redis_version" => "4.0"
|
||||||
"address" => "127.0.0.1",
|
],
|
||||||
"port" => 8000
|
"port" => 8000
|
||||||
],
|
],
|
||||||
"wan" => [
|
"check" => [
|
||||||
"address" => "172.26.221.211",
|
"node" => "t2.320",
|
||||||
"port" => 80
|
"checkId" => "service:redis1",
|
||||||
]
|
"name" => "NoSql health check",
|
||||||
],
|
"Annotations" => "Script based health check",
|
||||||
"meta" => [
|
"status" => "passing",
|
||||||
"redis_version" => "4.0"
|
"serviceID" => "redis1",
|
||||||
],
|
"definition" => [
|
||||||
"port" => 8000
|
"http" => "172.26.221.211:9527",
|
||||||
],
|
"interval" => "5s",
|
||||||
"check" => [
|
"timeout" => "1s",
|
||||||
"node" => "t2.320",
|
"deregisterCriticalServiceAfter" => "30s"
|
||||||
"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"
|
|
||||||
],
|
|
||||||
],
|
|
||||||
]
|
|
||||||
|
|
||||||
]
|
|
||||||
];
|
|
||||||
|
|||||||
Reference in New Issue
Block a user