使用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:~#

四、各服务关系总览

各服务关系

使用阿里云配置中心的配置。

阿里云配置中心配置文件内容对象会直接覆盖到本机config对象。以后修改配置信息就不需要重启服务了。
安装依赖

composer require hyperf/config-aliyun-acm

config/autoload 文件夹内增加一个 aliyun_acm.php文件内容如下:

<?php
return [
    // 是否开启配置中心的接入流程,为 true 时会自动启动一个 ConfigFetcherProcess 进程用于更新配置
    'enable' => true,
    // 是否使用独立进程来拉取config,如果否则将在worker内以协程方式拉取
    'use_standalone_process' => true,
    // 配置更新间隔(秒)
    'interval' => 5,
    // 阿里云 ACM 断点地址,取决于您的可用区
    'endpoint' => env('ALIYUN_ACM_ENDPOINT', 'acm.aliyun.com'),
    // 当前应用需要接入的 Namespace
    'namespace' => env('ALIYUN_ACM_NAMESPACE', '733e4119-6098-4491-9959a866ceb24'),
    // 您的配置对应的 Data ID
    'data_id' => env('ALIYUN_ACM_DATA_ID', 'hyperf-demo'),
    // 您的配置对应的 Group
    'group' => env('ALIYUN_ACM_GROUP', 'DEFAULT_GROUP'),
    // 您的阿里云账号的 Access Key
    'access_key' => env('ALIYUN_ACM_AK', 'LTAI4G8MwXoLGd'),
    // 您的阿里云账号的 Secret Key
    'secret_key' => env('ALIYUN_ACM_SK', 'YXLViuYKqM5WoRrCon4U'),
];

或者在根目录.env 添加:

ALIYUN_ACM_NAMESPACE=733e4119-6098-4491-9950-4b24
ALIYUN_ACM_DATA_ID=hyperf-demo
ALIYUN_ACM_GROUP=DEFAULT_GROUP
ALIYUN_ACM_AK=LTAI4G8MwXosb2S
ALIYUN_ACM_SK=YXLViuYKqM5W

然后

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,009评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,808评论 2 378
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,891评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,283评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,285评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,409评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,809评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,487评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,680评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,499评论 2 318
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,548评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,268评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,815评论 3 304
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,872评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,102评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,683评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,253评论 2 341