Hyperf微服务——五、JsonRpc远程调用
一、JsonRpc请求的实现、
调用链从上到下
namespace App\JsonRpc;
//请求入口 通过容器获取接口对象
class IndexController extends AbstractController
{
public function index()
{
$user_info = ApplicationContext::getContainer()->get(UserInfoInterface::class);
return $user_info->getUserInfoById(1);
}
}
namespace App\JsonRpc;
//服务启动,自动生成服务提供者的接口代理文件
class UserInfoInterface_7be0c5bab4e9d0b2671b5482e5fa29f4 extends \Hyperf\RpcClient\Proxy\AbstractProxyService implements UserInfoInterface
{
public function getUserInfoById($id)
{
//通过抽象代理文件的__call方法进行调用
return $this->client->__call(__FUNCTION__, func_get_args());
}
}
namespace Hyperf\RpcClient;
//rpc客户端的底层实现
class ServiceClient extends AbstractServiceClient
{
/**
* @var MethodDefinitionCollectorInterface
*/
protected $methodDefinitionCollector;
/**
* @var string
*/
protected $serviceInterface;
/**
* @var NormalizerInterface
*/
private $normalizer;
public function __construct(ContainerInterface $container, string $serviceName, string $protocol = 'jsonrpc-http', array $options = [])
{
$this->serviceName = $serviceName;
$this->protocol = $protocol;
$this->setOptions($options);
parent::__construct($container);
$this->normalizer = $container->get(NormalizerInterface::class);
$this->methodDefinitionCollector = $container->get(MethodDefinitionCollectorInterface::class);
}
//真正的rpc调用方法
protected function __request(string $method, array $params, ?string $id = null)
{
if ($this->idGenerator instanceof IdGeneratorInterface && ! $id) {
$id = $this->idGenerator->generate();
}
//生成调用地址并发送消息体到服务提供者
$response = $this->client->send($this->__generateData($method, $params, $id));
if (! is_array($response)) {
throw new RequestException('Invalid response.');
}
$response = $this->checkRequestIdAndTryAgain($response, $id);
if (array_key_exists('result', $response)) {
$type = $this->methodDefinitionCollector->getReturnType($this->serviceInterface, $method);
if ($type->allowsNull() && $response['result'] === null) {
return null;
}
//消息体解码
return $this->normalizer->denormalize($response['result'], $type->getName());


1849

被折叠的 条评论
为什么被折叠?



