Hyperf-JsonRpc使用

Hyperf-JsonRpc使用

标签(空格分隔): php

安装扩展包

composer require hyperf/json-rpc
composer require hyperf/rpc-server
composer require hyperf/rpc-client

使用

服务有两种角色,一种是 服务提供者(ServiceProvider),即为其它服务提供服务的服务,另一种是 服务消费者(ServiceConsumer),即依赖其它服务的服务,一个服务既可能是 服务提供者(ServiceProvider),同时又是 服务消费者(ServiceConsumer)。而两者直接可以通过 服务契约 来定义和约束接口的调用,在 Hyperf 里,可直接理解为就是一个 接口类(Interface),通常来说这个接口类会同时出现在提供者和消费者下。

server.php

servers 下增加配置

        // jsonrpc-http 服务配置
        [
            'name' => 'jsonrpc-http',
            'type' => Server::SERVER_HTTP,
            'host' => '0.0.0.0',
            'port' => 9504,
            'sock_type' => SWOOLE_SOCK_TCP,
            'callbacks' => [
                Event::ON_REQUEST => [HyperfJsonRpcHttpServer::class, 'onRequest'],
            ],
        ],

services.php 标记要从何服务中心或者哪个节点 获取节点信息,服务中心配起来很麻烦

<?php
return [
    'consumers' => [
        [
            // 对应消费者类的 $serviceName
            'name' => 'UserServiceServer',
            // 这个消费者要从哪个服务中心获取节点信息,如不配置则不会从服务中心获取节点信息
//            'registry' => [
//                'protocol' => 'consul',
//                'address' => 'http://127.0.0.1:8500',
//            ],
            // 如果没有指定上面的 registry 配置,即为直接对指定的节点进行消费,通过下面的 nodes 参数来配置服务提供者的节点信息
            'nodes' => [
                ['host' => '127.0.0.1', 'port' => 9504],
            ],
        ]
    ],
];

目录结构

定义Server端来提供服务

// 定义接口,更加规范
<?php
declare(strict_types=1);

namespace AppRpcInter;

interface UserServiceInter
{
    public function getUserInfo(int $userId) : string;

    public function getUserList(int $page, int $pageSize, array $params = []) : string;
}


// server 
<?php
declare(strict_types=1);

namespace AppRpcServer;


use AppRpcInterUserServiceInter;
use AppUtilsResJson;
use HyperfDiAnnotationInject;
use HyperfRpcServerAnnotationRpcService;

/**
 * Rpc用户服务
 * Class RpcUserService
 * @package AppRpc
 * name: 服务名称全局唯一
 * protocol: 服务协议:jsonrpc-http, jsonrpc, jsonrpc-tcp-length-check
 * @RpcService(name="UserServiceServer", protocol="jsonrpc-http", server="jsonrpc-http", publishTo="consul")
 */
class UserServiceServer implements UserServiceInter
{

    /**
     * @Inject()
     * @var ResJson
     */
    public $resJson;


    /**
     * 获取用户信息
     * @param int $userId
     * @return string
     */
    public function getUserInfo(int $userId) : string
    {
        $array['user_id'] = $userId;
        $array['user_name'] = "PHP";
        return $this->resJson->returnJsonString(ResJson::CODE_200, $array);
    }


    /**
     * 获取用户列表
     * @param int $page 页码数
     * @param int $pageSize 每页条数
     * @param array $params 可选参数
     * @return string
     */
    public function getUserList(int $page, int $pageSize, array $params = []): string
    {
        $user[] = ['user_id' => 1, 'user_name' => 'Bill'];
        $user[] = ['user_id' => 2, 'user_name' => 'Taylor'];
        $user[] = ['user_id' => 3, 'user_name' => 'Jerry'];
        return $this->resJson->returnJsonString(ResJson::CODE_200, $user);
    }
}

定义服务消费者

<?php
declare(strict_types=1);

namespace AppRpcClient;

use AppRpcInterUserServiceInter;
use HyperfRpcClientAbstractServiceClient;

class UserServiceClient extends AbstractServiceClient implements UserServiceInter
{
    /**
     * 服务提供者的服务名称
     * @var string
     */
    protected $serviceName = "UserServiceServer";


    /**
     * 定义对应服务提供者的服务协议
     * @var string
     */
    protected $protocol = 'jsonrpc-http';


    public function getUserInfo(int $userId) : string
    {
        return $this->__request(__FUNCTION__, compact('userId'));
    }


    public function getUserList(int $page, int $pageSize, array $params = []): string
    {
        return $this->__request(__FUNCTION__, compact('page', 'pageSize', 'params'));
    }
}

使用Rpc服务

在config/autoload/dependencies.php 内定义 UserServiceInter 和 UserServiceClient 的关系

// 这样便可以通过注入 UserServiceInter 接口来使用客户端了
AppRpcInterUserServiceInter::class => AppRpcClientUserServiceClient::class,

这样便可以通过注入 UserServiceInter 接口来使用客户端了。

Controller 代码:

<?php

declare(strict_types=1);

namespace AppAdminController;


use AppAdminModelUserModel;
use AppAdminServiceUserService;
use AppEventAppException;
use AppRpcInterUserServiceInter;
use HyperfDbConnectionDb;
use HyperfDiAnnotationInject;
use HyperfHttpServerAnnotationAutoController;
use HyperfUtilsContext;
use PsrEventDispatcherEventDispatcherInterface;
use function _HumbugBoxa5be08ba8ddbReactPromiseStreamfirst;

/**
 * 用户控制器
 * Class UserController
 * @package AppAdminController
 * @AutoController()
 */
class UserController extends AdminBaseController
{
    /**
     * @Inject()
     * @var UserServiceInter
     */
    public $rpcUserService;


    public function rpc()
    {
        $arr = $this->rpcUserService->getUserInfo(919);
        var_dump($arr);
        return $arr;
    }


    public function rpcuserlist()
    {
        $arr = $this->rpcUserService->getUserList(1, 10);
        var_dump($arr);
        return $arr;
    }
}

重启hyperf 运行

原文地址:https://www.cnblogs.com/yanweifeng/p/14452450.html