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());
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Justin-D

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值