Files
kiri-core/Rpc/Producer.php
T
as2252258@163.com b9e2704313 modify
2021-03-23 02:31:03 +08:00

78 lines
1.8 KiB
PHP

<?php
namespace Rpc;
use Snowflake\Abstracts\Component;
use Snowflake\Abstracts\Config;
use Snowflake\Snowflake;
/**
* Class Producer
* @package Rpc
*/
class Producer extends Component
{
private array $producers = [];
/**
* @param $name
* @return Producer|bool
* @throws \ReflectionException
* @throws \Snowflake\Exception\ComponentException
* @throws \Snowflake\Exception\ConfigException
* @throws \Snowflake\Exception\NotFindClassException
*/
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 mixed
* @throws \ReflectionException
* @throws \Snowflake\Exception\ComponentException
* @throws \Snowflake\Exception\ConfigException
* @throws \Snowflake\Exception\NotFindClassException
*/
public function __get($name): mixed
{
return $this->get($name); // TODO: Change the autogenerated stub
}
/**
* @param $name
* @param $rand
* @return string
*/
private function getName($name, $rand)
{
return 'rpc.client.' . $name . '.' . $rand['host'];
}
}