侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

在hyperf框架中使用基于protobuf的RPC生成器实现rpc服务

swoole  /  管理员 发布于 2年前   890

ROC RPC PHP演示git

https://github.com/Gemini-D/roc-rpc-php-demo

环境架构:

hyperf2.2
ROCGenerator


安装RPC生成工具

有两种安装方式

1.使用源码

2.使用打包好的二进制文件

git:

https://github.com/hyperf/roc-generator


编写rpc.proto文件

syntax = "proto3";

option php_namespace = "ROC\\RPC";

package rpc;

service UserInterface {
rpc info(UserInput) returns (User) {}}

message UserInput{
uint64 id = 1;}

message User {
uint64 id = 1; string name = 2; uint32 gender = 3;}



根据文件生成代码

cd rpc
roc-php gen:roc rpc.proto -O src

接下来,我们就可以在 rpc/src 目录下看到了生成的文件。


完善自定义rpc组件代码

正常情况下,我们需要按照官网配置,增加对应配置文件,但这样会比较麻烦,

所以我们通过事件的方式,将对应配置自动加载进来


编写监听器

增加rpc/src/Listener/BootConsumerListener

<?php

declare(strict_types=1);
/**
* This file is part of Hyperf. * * @link     https://www.hyperf.io * @document https://hyperf.wiki * @contact  [email protected] * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE */namespace ROC\RPC\Listener;

use Hyperf\Contract\ConfigInterface;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Framework\Event\BootApplication;
use Hyperf\RpcMultiplex\Constant;
use Psr\Container\ContainerInterface;
use ROC\RPC\UserInterface;

/**
* Must handle the event before `Hyperf\RpcClient\Listener\AddConsumerDefinitionListener`. * You can set ROC\RPC\Listener\BootConsumerListener::class => 99. */class BootConsumerListener implements ListenerInterface
{
/** * @var ContainerInterface */ private $container;
public function __construct(ContainerInterface $container) { $this->container = $container; }
public function listen(): array { return [ BootApplication::class, ]; }
public function process(object $event): void { $config = $this->container->get(ConfigInterface::class);
$consumers = $config->get('services.consumers', []); $services = [ UserInterface::class => ['127.0.0.1', 9504], ];
foreach ($services as $interface => [$host, $port]) { $consumers[] = static::getDefaultConsumer($interface, $host, $port); }
$config->set('services.consumers', $consumers); }
public static function getDefaultConsumer(string $interface, string $host, int $port): array { return [ 'name' => $interface, 'service' => $interface, 'id' => $interface, 'protocol' => Constant::PROTOCOL_DEFAULT, 'load_balancer' => 'random', 'nodes' => [ ['host' => $host, 'port' => $port], ], 'options' => [ 'connect_timeout' => 5.0, 'recv_timeout' => 5.0, 'settings' => [ // 包体最大值,若小于 Server 返回的数据大小,则会抛出异常,故尽量控制包体大小
'package_max_length' => 1024 * 1024 * 2, ], // 重试次数,默认值为 2 'retry_count' => 2, // 重试间隔,毫秒
'retry_interval' => 10, // 多路复用客户端数量
'client_count' => 4, // 心跳间隔
'heartbeat' => 20, ], ]; }}


编写RPC服务端代码

增加对应仓库

首先我们现在 server/composer.json 中增加对应的仓库配置

{
"repositories": { "rpc": { "type": "path", "url": "../rpc" } }}

接下来再通过执行脚本,载入对应组件包

composer require roc/rpc


导入RPC相关组件

composer require "hyperf/rpc-client:3.0.x-dev" -W
composer require "hyperf/rpc:3.0.x-dev" -W
composer require "hyperf/rpc-multiplex:3.0.x-dev" -W
composer require "hyperf/rpc-server:3.0.x-dev" -W

ps:

因为相关的代码,还没有发布Release版本,所以需要导入x-dev包


增加RPC服务配置

让我们修改config/server.php文件,增加rpc相关配置

<?php

declare(strict_types=1);
/**
* This file is part of Hyperf. * * @link     https://www.hyperf.io * @document https://hyperf.wiki * @contact  [email protected] * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE */use Hyperf\Engine\Constant\SocketType;
use Hyperf\Server\Event;
use Hyperf\Server\Server;

return [
'mode' => SWOOLE_BASE, 'type' => Hyperf\Server\CoroutineServer::class, 'servers' => [ [ 'name' => 'http', 'type' => Server::SERVER_HTTP, 'host' => '0.0.0.0', 'port' => 9501, 'sock_type' => SocketType::TCP, 'callbacks' => [ Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'], ], ], [ 'name' => 'rpc', 'type' => Server::SERVER_BASE, 'host' => '0.0.0.0', 'port' => 9504, 'sock_type' => SWOOLE_SOCK_TCP, 'callbacks' => [ Event::ON_RECEIVE => [Hyperf\RpcMultiplex\TcpServer::class, 'onReceive'], ], 'settings' => [ 'open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4, 'package_max_length' => 1024 * 1024 * 2, ], ], ], 'settings' => [ 'enable_coroutine' => true, 'worker_num' => 4, 'pid_file' => BASE_PATH . '/runtime/hyperf.pid', 'open_tcp_nodelay' => true, 'max_coroutine' => 100000, 'open_http2_protocol' => true, 'max_request' => 0, 'socket_buffer_size' => 2 * 1024 * 1024, 'package_max_length' => 2 * 1024 * 1024, ], 'callbacks' => [ Event::ON_BEFORE_START => [Hyperf\Framework\Bootstrap\ServerStartCallback::class, 'beforeStart'], Event::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'], Event::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'], Event::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'], ],];


增加服务实现

新增app/RPC/UserService.php 文件,增加以下代码

<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf. * * @link     https://www.hyperf.io * @document https://hyperf.wiki * @contact  [email protected] * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE */namespace App\RPC;
use Hyperf\RpcMultiplex\Constant;
use Hyperf\RpcServer\Annotation\RpcService;
use ROC\RPC\User;
use ROC\RPC\UserInput;
use ROC\RPC\UserInterface;
#[RpcService(name: UserInterface::class, server: 'rpc', protocol: Constant::PROTOCOL_DEFAULT)]
class UserService implements UserInterface
{
 public function info(UserInput $input): User { return new User( $input->id, 'Hyperf', 1 ); }
}

配置监听器

修改server/config/autoload/listeners.php

<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf. * * @link     https://www.hyperf.io * @document https://hyperf.wiki * @contact  [email protected] * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE */return [
 Hyperf\ExceptionHandler\Listener\ErrorExceptionHandler::class, Hyperf\Command\Listener\FailToHandleListener::class, ROC\RPC\Listener\BootConsumerListener::class => 99,];


测试RPC

编写RegisterProtocolListener

因为默认的RPC组件,使用的是默认的Normalizer,而代码生成的接口文件,

是需要支持Json转Object,所以我们需要进行替换

<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf. * * @link     https://www.hyperf.io * @document https://hyperf.wiki * @contact  [email protected] * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE */namespace App\Listener;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Framework\Event\BootApplication;
use Hyperf\Rpc\ProtocolManager;
use Hyperf\RpcMultiplex\Constant;
use Hyperf\RpcMultiplex\DataFormatter;
use Hyperf\RpcMultiplex\Packer\JsonPacker;
use Hyperf\RpcMultiplex\PathGenerator;
use Hyperf\RpcMultiplex\Transporter;
use Hyperf\Utils\Serializer\JsonDeNormalizer;
use Psr\Container\ContainerInterface;
#[Listener(priority: -1)]
class RegisterProtocolListener implements ListenerInterface
{
 public function __construct(protected ContainerInterface $container) { }
 public function listen(): array { return [ BootApplication::class, ]; }
 public function process(object $event): void { $this->container->get(ProtocolManager::class)->register(Constant::PROTOCOL_DEFAULT, [ 'packer' => JsonPacker::class, 'transporter' => Transporter::class, 'path-generator' => PathGenerator::class, 'data-formatter' => DataFormatter::class, 'normalizer' => JsonDeNormalizer::class, ]); }}


编写测试代码

<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf. * * @link     https://www.hyperf.io * @document https://hyperf.wiki * @contact  [email protected] * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE */namespace App\Controller;
use Hyperf\Di\Annotation\Inject;
use ROC\RPC\UserInput;
use ROC\RPC\UserInterface;
class IndexController extends Controller
{
 #[Inject] protected UserInterface $user;
 public function index() { $result = $this->user->info(new UserInput(1));
 return $this->response->success($result); }}

启动服务

php bin/hyperf.php start

访问接口

curl http://127.0.0.1:9501/
{"code":0,"data":{"id":1,"name":"Hyperf","gender":1}}

  • 上一条:
    性能测试工具、HTTP基准测试工具:wrk
    下一条:
    在go语言中用Time.Add()或Time.AddDate()函数减去时间来计算过去的日期
  • 昵称:

    邮箱:

    1条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • swoole协程通信之数据处理协程对数据进行读写,保存到协程上下文示例(0个评论)
    • swoole redis连接池应用优化之多协程频繁访问redis(0个评论)
    • php中使用hyperf框架调用讯飞星火大模型实现国内版chatgpt功能示例(2个评论)
    • php中使用hyperf框架调用文心千帆大模型实现国内版chatgpt功能示例(0个评论)
    • 在hyperf框架中使用基于protobuf的RPC生成器实现rpc服务(1个评论)
    • 近期文章
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-09
    • 2020-03
    • 2020-06
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-11
    • 2022-03
    • 2022-05
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-07
    • 2023-08
    • 2023-11
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客