安装
安装docker hyperf
安装 hyperf-rpc-server-v8 (服务端)
docker run --name hyperf-rpc-server-v8 \
-v /www/docker/hyperf-rpc-server:/data/project \
-w /data/project \
-p 9508:9501 -it \
--privileged -u root \
--entrypoint /bin/sh \
hyperf/hyperf:8.1-alpine-v3.18-swoole
安装 hyperf-rpc-client-v8 (客户端)
docker run --name hyperf-rpc-client-v8 \
-v /www/docker/hyperf-rpc-client:/data/project \
-w /data/project \
-p 9509:9501 -it \
--privileged -u root \
--entrypoint /bin/sh \
hyperf/hyperf:8.1-alpine-v3.18-swoole
(一)创建配置中心服务
安装nacos配置中心
composer require hyperf/config-center
composer require hyperf/config-nacos
配置文件config/aoutload/config_center.php
注意:
这里的
'group_name' => 'DEFAULT_GROUP'
, 对应注册中心的 Group
'namespace_id' => 'public'
, 对应注册中心的 命名空间
public
<?phpdeclare(strict_types=1);
/*** This file is part of Hyperf.** @link https://www.hyperf.io* @document https://hyperf.wiki* @contact group@hyperf.io* @license https://github.com/hyperf/hyperf/blob/master/LICENSE*/
use Hyperf\ConfigCenter\Mode;use function Hyperf\Support\env;return ['enable' => (bool) env('CONFIG_CENTER_ENABLE', true),'driver' => env('CONFIG_CENTER_DRIVER', 'nacos'),'mode' => env('CONFIG_CENTER_MODE', Mode::PROCESS),'drivers' => ['nacos' => ['driver' => Hyperf\ConfigNacos\NacosDriver::class,'merge_mode' => Hyperf\ConfigNacos\Constants::CONFIG_MERGE_OVERWRITE,'interval' => 3,'default_key' => 'nacos_config','listener_config' => [// dataId, group, tenant, type, content'nacos_config' => ['tenant' => 'public', // corresponding with service.namespaceId'data_id' => 'config_user','group' => 'DEFAULT_GROUP',],'nacos_config.data' => ['data_id' => 'config_user','group' => 'DEFAULT_GROUP','type' => 'json',],'nacos_config.member' => ['data_id' => 'member','group' => 'DEFAULT_GROUP','type' => 'json',],],'client' => [// nacos server url like https://nacos.hyperf.io, Priority is higher than host:port// 'uri' => '','host' => '10.0.0.94','port' => 8848,'username' => null,'password' => null,'guzzle' => ['config' => null,]],],],
];
nacos配置文件
结果
控制器调用
public function index(){$user = $this->request->input('user', 'Hyperf');$method = $this->request->getMethod();$v = \Hyperf\Config\config('nacos_config');var_dump($v);return ['method' => $method,'message' => "Hello {$user}.",];}
(二)创建服务发现项目
composer create-project hyperf/hyperf-skeleton
服务端
安装json-rpc
如果没安装请先安装相关的插件
composer require hyperf/json-rpc
安装rpc-server
要使用 JSON RPC 服务端:
composer require hyperf/rpc-server
安装service-governance-nacos
composer require hyperf/service-governance-nacos
或指定版本
composer require hyperf/service-governance-nacos:v2.2.39
server.php配置文件
['name' => 'jsonrpc-http','type' => Server::SERVER_HTTP,'host' => '0.0.0.0','port' => 9504,'sock_type' => SWOOLE_SOCK_TCP,'callbacks' => [Event::ON_REQUEST => [\Hyperf\JsonRpc\HttpServer::class, 'onRequest'],],'options' => [// Whether to enable request lifecycle event'enable_request_lifecycle' => false,],],
nacos注册中心,推服务到注册中心,servers.php
注意:
这里的
'group_name' => 'DEFAULT_GROUP'
, 对应注册中心的 Group
'namespace_id' => 'public'
, 对应注册中心的 命名空间
public
<?php
/*** services.php** Created on 2024-08-27-14:30* Created by xxp 332410549@qq.com*/return ['enable' => [// 开启服务发现'discovery' => true,// 开启服务注册'register' => true,],// 服务消费者相关配置'consumers' => [],// 服务提供者相关配置'providers' => [],// 服务驱动相关配置'drivers' => [//consul注册中心驱动'consul' => ['uri' => 'http://127.0.0.1:8500','token' => '','check' => ['deregister_critical_service_after' => '90m','interval' => '1s',],],// 注册 nacos 服务发现驱动'nacos' => ['host' => '10.0.0.94','port' => 8848,// The nacos account info'username' => null,'password' => null,'guzzle' => ['config' => null,],'group_name' => 'DEFAULT_GROUP','namespace_id' => 'public','heartbeat' => 5,'ephemeral' => false, // 是否注册临时实例],],
];
查看结果
消费端
安装
安装json-rpc
如果没安装请先安装相关的插件
composer require hyperf/json-rpc
安装rpc-client
要使用 JSON RPC 客户端:
composer require hyperf/rpc-client
安装service-governance-nacos
composer require hyperf/service-governance-nacos
或指定版本
composer require hyperf/service-governance-nacos:v2.2.39
如果没有安装service-governance-nacos
,则会有报错
hyperf Invalid protocol of registry nacos[156]
自动创建代理消费者类
不常用,可以看下面的配置复用
<?php
return [// 此处省略了其它同层级的配置'consumers' => [[// name 需与服务提供者的 name 属性相同'name' => 'CalculatorService',// 服务接口名,可选,默认值等于 name 配置的值,如果 name 直接定义为接口类则可忽略此行配置,如 name 为字符串则需要配置 service 对应到接口类'service' => \App\Interfaces\CalculatorServiceInterface::class,// 对应容器对象 ID,可选,默认值等于 service 配置的值,用来定义依赖注入的 key'id' => \App\Interfaces\CalculatorServiceInterface::class,// 服务提供者的服务协议,可选,默认值为 jsonrpc-http// 可选 jsonrpc-http jsonrpc jsonrpc-tcp-length-check'protocol' => 'jsonrpc-http',// 负载均衡算法,可选,默认值为 random'load_balancer' => 'random',// 这个消费者要从哪个服务中心获取节点信息,如不配置则不会从服务中心获取节点信息'registry' => ['protocol' => 'nacos','address' => 'http://10.0.0.94:8848',],// 如果没有指定上面的 registry 配置,即为直接对指定的节点进行消费,通过下面的 nodes 参数来配置服务提供者的节点信息'nodes' => [['host' => '127.0.0.1', 'port' => 9504],],// 配置项,会影响到 Packer 和 Transporter'options' => ['connect_timeout' => 5.0,'recv_timeout' => 5.0,'settings' => [// 根据协议不同,区分配置'open_eof_split' => true,'package_eof' => "\r\n",// 'open_length_check' => true,// 'package_length_type' => 'N',// 'package_length_offset' => 0,// 'package_body_offset' => 4,],// 重试次数,默认值为 2,收包超时不进行重试。暂只支持 JsonRpcPoolTransporter'retry_count' => 2,// 重试间隔,毫秒'retry_interval' => 100,// 使用多路复用 RPC 时的心跳间隔,null 为不触发心跳'heartbeat' => 30,// 当使用 JsonRpcPoolTransporter 时会用到以下配置'pool' => ['min_connections' => 1,'max_connections' => 32,'connect_timeout' => 10.0,'wait_timeout' => 3.0,'heartbeat' => -1,'max_idle_time' => 60.0,],],]],
];
配置复用
通常来说,一个服务消费者会同时消费多个服务提供者,当我们通过服务中心来发现服务提供者时, config/autoload/services.php 配置文件内就可能会重复配置很多次 registry 配置,但通常来说,我们的服务中心可能是统一的,也就意味着多个服务消费者配置都是从同样的服务中心去拉取节点信息,此时我们可以通过 PHP 变量 或 循环 等 PHP 代码来实现配置文件的生成。
通过 PHP 变量生成配置
<?php
$registry = ['protocol' => 'consul','address' => 'http://127.0.0.1:8500',
];
return [// 下面的 FooService 和 BarService 仅示例多服务,并不是在文档示例中真实存在的'consumers' => [['name' => 'CalculatorService','service' => \App\JsonRpc\CalculatorServiceInterface::class,'registry' => $registry,],],
];
通过循环生成配置
<?php
return [// 此处省略了其它同层级的配置'consumers' => value(function () {$consumers = [];// 这里示例自动创建代理消费者类的配置形式,顾存在 name 和 service 两个配置项,这里的做法不是唯一的,仅说明可以通过 PHP 代码来生成配置// 下面的 FooServiceInterface 和 BarServiceInterface 仅示例多服务,并不是在文档示例中真实存在的$services = ['FooService' => App\JsonRpc\FooServiceInterface::class,'BarService' => App\JsonRpc\BarServiceInterface::class,];foreach ($services as $name => $interface) {$consumers[] = ['name' => $name,'service' => $interface,'registry' => ['protocol' => 'consul','address' => 'http://127.0.0.1:8500',]];}return $consumers;}),
];
控制器调用
接口代码
这个接口与服务端是一致的
<?php
/*** CalculatorServiceInterface.php** Created on 2024-08-27-14:50* Created by xxp 332410549@qq.com*/
declare(strict_types=1);namespace App\JsonRpc;interface CalculatorServiceInterface
{public function sum(int $v1, int $v2): int;}
属性注入调用
控制器代码
<?phpdeclare(strict_types=1);
namespace App\Controller;use App\JsonRpc\CalculatorServiceInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;;#[AutoController(prefix: "index")]
class IndexController extends AbstractController
{#[Inject]private CalculatorServiceInterface $cal;public function client(){$res = $this->cal->sum(1,2);return '1 + 2 = '.$res;}
}
结果:
容器调用
<?phpdeclare(strict_types=1);
/*** This file is part of Hyperf.** @link https://www.hyperf.io* @document https://hyperf.wiki* @contact group@hyperf.io* @license https://github.com/hyperf/hyperf/blob/master/LICENSE*/namespace App\Controller;use App\JsonRpc\CalculatorServiceInterface;
use Hyperf\Context\ApplicationContext;
use Hyperf\HttpServer\Annotation\AutoController;;#[AutoController(prefix: "index")]class IndexController extends AbstractControllerpublic function container(){$client = ApplicationContext::getContainer()->get(CalculatorServiceInterface::class);$res = $client->sum(100,200);return '100 + 200 = '.$res;}}
问题
- 如果服务端宕机,则会有下面的报错