Files
kiri-core/Rpc/Producer.php
T
2021-03-23 10:30:14 +08:00

84 lines
1.9 KiB
PHP

<?php
namespace Rpc;
use Exception;
use ReflectionException;
use Snowflake\Abstracts\Component;
use Snowflake\Abstracts\Config;
use Snowflake\Exception\ComponentException;
use Snowflake\Exception\ConfigException;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake;
/**
* Class Producer
* @package Rpc
*/
class Producer extends Component
{
private array $producers = [];
/**
* @param $name
* @return Producer|bool
* @throws ReflectionException
* @throws ComponentException
* @throws ConfigException
* @throws NotFindClassException
* @throws Exception
*/
public function get($name): Client|bool
{
if (empty($this->producers)) {
$this->producers = Config::get('rpc.producers');
}
if (empty($this->producers)) {
return $this->addError('Empty by rpc service');
}
if (!isset($this->producers[$name])) {
return $this->addError('Unknown rpc service');
}
$rand = $this->producers[$name][array_rand($this->producers[$name])];
if (Snowflake::app()->has($this->getName($name, $rand))) {
return Snowflake::app()->get($this->getName($name, $rand));
}
return Snowflake::app()->set($this->getName($name, $rand), [
'class' => Client::class,
'config' => $rand
]);
}
/**
* @param $name
* @return Client|bool
* @throws ReflectionException
* @throws ComponentException
* @throws ConfigException
* @throws NotFindClassException
*/
public function __get($name): Client|bool
{
return $this->get($name); // TODO: Change the autogenerated stub
}
/**
* @param $name
* @param $rand
* @return string
*/
private function getName($name, $rand): string
{
return 'rpc.client.' . $name . '.' . $rand['host'];
}
}