使用Hyperf框架搭建jsonrpc服务

一、开发项目划分与搭建

JSON RPC 是一种基于 JSON 格式的轻量级的 RPC 协议标准,易于使用和阅读。在 Hyperf 里由 hyperf/json-rpc 组件来实现,可自定义基于 HTTP 协议来传输,或直接基于 TCP 协议来传输

本次我选择使用基于 TCP 协议的 jsonrpc 协议来搭建服务。

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

本次我搭建了一个服务提供者 calculate,为其他服务提供计算功能;一个消费者,通过 jsonrpc 协议调用 calculate 提供的计算功能。搭建过程如下:

1、搭建 calculate 服务提供者

composer create-project hyperf/hyperf-skeleton calculate

Which RPC protocol do you want to use ?
  [1] JSON-RPC with Service Governance
  [2] JSON-RPC
  [3] gRPC
  [n] None of the above
  Make your selection or type a composer package name and version (n): 2
  
Which config center do you want to use ?
  [1] Apollo
  [2] Aliyun ACM
  [n] None of the above
  Make your selection or type a composer package name and version (n): 1
  
Do you want to use hyperf/constants component ?
  [1] yes
  [n] None of the above
  Make your selection (n): 1
  
Do you want to use hyperf/async-queue component ? (A simple redis queue component)
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n): 1
  
Do you want to use hyperf/amqp component ?
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n): 1
  
Do you want to use hyperf/model-cache component ?
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n): 1
  
Do you want to use hyperf/elasticsearch component ?
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n): n
  
Do you want to use hyperf/tracer component ? (A open tracing protocol component, adapte with Zipkin etc.)
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n): 1

2、搭建 gateway 服务消费者

composer create-project hyperf/hyperf-skeleton gateway

Which RPC protocol do you want to use ?
  [1] JSON-RPC with Service Governance
  [2] JSON-RPC
  [3] gRPC
  [n] None of the above
  Make your selection or type a composer package name and version (n): 2
  
Which config center do you want to use ?
  [1] Apollo
  [2] Aliyun ACM
  [n] None of the above
  Make your selection or type a composer package name and version (n): 1
  
Do you want to use hyperf/constants component ?
  [1] yes
  [n] None of the above
  Make your selection (n): 1
  
Do you want to use hyperf/async-queue component ? (A simple redis queue component)
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n): 1
  
Do you want to use hyperf/amqp component ?
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n): 1
  
Do you want to use hyperf/model-cache component ?
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n): 1
  
Do you want to use hyperf/elasticsearch component ?
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n): n
  
Do you want to use hyperf/tracer component ? (A open tracing protocol component, adapte with Zipkin etc.)
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n): 1

二、JSON RPC服务开发与配置

1、calculate 功能开发

app 目录结构

app
    Constants
    Controller
    Exception
    JsonRpc
        CalculatorService.php
        CalculatorServiceInterface.php
    Listener
    Model
    Process

app\JsonRpc\CalculatorService.php

<?php
namespace App\JsonRpc;
use Hyperf\RpcServer\Annotation\RpcService;
/**
 * Class CalculatorService
 * @RpcService(name="CalculatorService", protocol="jsonrpc", server="jsonrpc")
 */
class CalculatorService implements CalculatorServiceInterface
{
    public function add(int $v1, int $v2): int
    {
        return $v1 + $v2;
    }
}

app\JsonRpc\CalculatorServiceInterface.php

<?php
declare(strict_types=1);
namespace App\JsonRpc;
interface CalculatorServiceInterface
{
    public function add(int $v1, int $v2): int;
}

calculate 服务配置 config\autoload\server.php

<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */
use Hyperf\Server\Server;
use Hyperf\Server\SwooleEvent;
return [
    'mode' => SWOOLE_PROCESS,
    'servers' => [
        [
            'name' => 'jsonrpc',
            'type' => Server::SERVER_BASE,
            'host' => '0.0.0.0',
            'port' => 9501,
            'sock_type' => SWOOLE_SOCK_TCP,
            'callbacks' => [
                SwooleEvent::ON_RECEIVE => [Hyperf\JsonRpc\TcpServer::class, 'onReceive'],
            ],
            'settings' => [
                'open_eof_split' => true,
                'package_eof' => "\r\n",
            ]
        ],
    ],
    'settings' => [
        'enable_coroutine' => true,
        'worker_num' => swoole_cpu_num(),
        'pid_file' => BASE_PATH . '/runtime/hyperf.pid',
        'open_tcp_nodelay' => true,
        'max_coroutine' => 100000,
        'open_http2_protocol' => true,
        'max_request' => 100000,
        'socket_buffer_size' => 2 * 1024 * 1024,
    ],
    'callbacks' => [
        SwooleEvent::ON_BEFORE_START => [Hyperf\Framework\Bootstrap\ServerStartCallback::class, 'beforeStart'],
        SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'],
        SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'],
    ],
];

2、gateway 消费者功能开发

app 目录结构

app
    Constants
    Controller
        IndexController.php
    Exception
    JsonRpc
        CalculatorServiceInterface.php
    Listener
    Model
    Process

app\JsonRpc\CalculatorServiceInterface.php

<?php
declare(strict_types=1);
namespace App\JsonRpc;
interface CalculatorServiceInterface
{
    public function add(int $v1, int $v2): int;
}

config\routes.php

<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */
use Hyperf\HttpServer\Router\Router;
Router::addRoute(['GET', 'POST', 'HEAD'], '/', 'App\Controller\IndexController@index');
Router::get('/add', 'App\Controller\IndexController@add');

app\Controller\IndexController.php

<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */
namespace App\Controller;
use Hyperf\Utils\Context;
use Hyperf\Utils\Coroutine;
use Hyperf\Utils\Parallel;
use Hyperf\Utils\ApplicationContext;
use App\JsonRpc\CalculatorServiceInterface;
use App\JsonRpc\MathValue;
class IndexController extends AbstractController
{
    public function index()
    {
        $user = $this->request->input('user', 'Hyperf');
        $method = $this->request->getMethod();
        return [
            'method' => $method,
            'message' => "Hello {$user}.",
        ];
    }
    public function add()
    {
        $client = ApplicationContext::getContainer()->get(CalculatorServiceInterface::class);
        $value = $client->add(10, 20);
        return $value;
    }
}

gateway 服务配置 config\autoload\server.php

<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */
use Hyperf\Server\Server;
use Hyperf\Server\SwooleEvent;
return [
    'mode' => SWOOLE_PROCESS,
    'servers' => [
        [
            'name' => 'http',
            'type' => Server::SERVER_HTTP,
            'host' => '0.0.0.0',
            'port' => 9500,
            'sock_type' => SWOOLE_SOCK_TCP,
            'callbacks' => [
                SwooleEvent::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'],
            ],
        ],
    ],
    'settings' => [
        'enable_coroutine' => true,
        'worker_num' => swoole_cpu_num(),
        'pid_file' => BASE_PATH . '/runtime/hyperf.pid',
        'open_tcp_nodelay' => true,
        'max_coroutine' => 100000,
        'open_http2_protocol' => true,
        'max_request' => 100000,
        'socket_buffer_size' => 2 * 1024 * 1024,
    ],
    'callbacks' => [
        SwooleEvent::ON_BEFORE_START => [Hyperf\Framework\Bootstrap\ServerStartCallback::class, 'beforeStart'],
        SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'],
        SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'],
    ],
];

config\autoload\services.php

<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */
return [
    'consumers' => [
        [
            // name 需与服务提供者的 name 属性相同
            'name' => 'CalculatorService',
            // 服务接口名,可选,默认值等于 name 配置的值,如果 name 直接定义为接口类则可忽略此行配置,如 name 为字符串则需要配置 service 对应到接口类
            'service' => \App\JsonRpc\CalculatorServiceInterface::class,
            // 对应容器对象 ID,可选,默认值等于 service 配置的值,用来定义依赖注入的 key
            'id' => \App\JsonRpc\CalculatorServiceInterface::class,
            // 服务提供者的服务协议,可选,默认值为 jsonrpc-http
            'protocol' => 'jsonrpc',
            // 负载均衡算法,可选,默认值为 random
            'load_balancer' => 'random',
            // 这个消费者要从哪个服务中心获取节点信息,如不配置则不会从服务中心获取节点信息
//            'registry' => [
//                'protocol' => 'consul',
//                'address' => 'http://127.0.0.1:8500',
//            ],
            // 如果没有指定上面的 registry 配置,即为直接对指定的节点进行消费,通过下面的 nodes 参数来配置服务提供者的节点信息
            'nodes' => [
                ['host' => '127.0.0.1', 'port' => 9501],
            ],
        ]
    ],
];

三、服务启动与通信演示

1、启动 calculate 服务

root@cosyphp-VirtualBox:~# cd /home/wwwroot/calculate/
root@cosyphp-VirtualBox:/home/wwwroot/calculate# php bin/hyperf.php start

2、启动 gateway 服务

root@cosyphp-VirtualBox:~# cd /home/wwwroot/gateway/
root@cosyphp-VirtualBox:/home/wwwroot/gateway# php bin/hyperf.php start

3、请求 gateway 服务

root@cosyphp-VirtualBox:~# curl http://127.0.0.1:9500/add
30
root@cosyphp-VirtualBox:~#

四、各服务关系总览

M先生博客
请先登录后发表评论
  • latest comments
  • 总共0条评论