Hyperf2.X搭建基于JSON-RPC与Consul的微服务
作者:温新
时间:2021-11-20
这2天简单的操作了下Hyerpf,一直有听过它,但没有用过它。用它的时候主要用于UDP的测试与微服务的搭建。花了一天的时间,还有很多不懂,对于微服务的实现,简单的做个记录。
本次实现,基于Hyperf自带的JSON-RPC实现的服务务。
环境:CentOS8.0
为了确保成功,建议按照本文顺序操作,当然了,也可以不按照这个顺序。
安装Consul服务
官方网址:https://www.consul.io/downloads
这上面有详细的安装,直接复制过来即可。
第一步:安装Consul
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install consul
第二步:启动Consul
// 查看是否安装成功
[root@localhost ~]# consul
Usage: consul [--version] [--help] <command> [<args>]
// 创建目录
mkdir -p /tmp/consul/config /tmp/consul/config
// 启动consul
consul agent -server -ui -dev -data-dir=/tmp/consul -config-dir=/tmp/consul -client 0.0.0.0 -bind 0.0.0.0
// 浏览器访问
192.168.157.128:8500
参数解释
agent 运行consul;
-server 服务端节点模式;
-client 客户端模式,http dns,默认127.0.0.1,回环令牌网址;
-bind 绑定的内部通讯地址,默认0.0.0.0
-ui 内置web ui界面(可视化界面);
-config-dir配置文件所在文件夹,会加载其下所有配置文件;
-data-dir 状态数据存储文件夹,所有的节点都需要;
启动consul
,用户浏览器访问,会出现可视化界面,会看到一个默认的consul
服务。**consul这个界面不要关闭。**接下来操作服务提供者和服务消费者操作。
服务器端-Hyperf微服务配置
第一步:Hyerpf实现微服务的依赖安装
// 安装json-rpc
composer require hyperf/json-rpc
// 安装json rpc服务器端
composer require hyperf/rpc-server
// 微服务接入层依赖
composer require hyperf/service-governance
// 注册微服务
composer require hyperf/service-governance-consul
第二步:安装hyperf
composer create-project hyperf/hyperf-skeleton hyper_server
参数时,参数的选择如下,仅作参考
Make your selection or type a time zone name, like Asia/Shanghai (n): n
Do you want to use Database (MySQL Client) ? n
Make your selection or type a composer package name and version (yes): n
// 这个地方要注意了,选择 2
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
[3] ETCD
[4] Nacos
[n] None of the above
Make your selection or type a composer package name and version (n): n
Do you want to use hyperf/constants component ? N
Do you want to use hyperf/async-queue component ? (A simple redis queue component) N
Do you want to use hyperf/amqp component ? N
Do you want to use hyperf/model-cache component ? N
Do you want to use hyperf/elasticsearch component ? N
Do you want to use hyperf/tracer component ? (An open tracing protocol component, adapte with Zipkin etc.) N
第三步:定义JSON RPC Server
// config/autoload/server.php
// 注意:不覆盖。我这里只是新加,初始化的配置没有改动
'servers' => [
[
'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'],
],
],
],
第四步:定义服务提供者
1)创建一个interface
// 文件位置。没有目录,自行自己创建
// app/JsonRpc/CalculatorServiceInterface.php
<?php
namespace App\JsonRpc;
interface CalculatorServiceInterface
{
public function add(int $a, int $b): int;
}
这个 Interface 是必须的。我在测试过程中,没有使用 Interface 均是报错。
2)实现接口
// app/JsonRpc/CalculatorService.php
<?php
namespace App\JsonRpc;
use Hyperf\RpcServer\Annotation\RpcService;
/**
* @RpcService(name="CalculatorService", protocol="jsonrpc-http", server="jsonrpc-http", publishTo="consul")
*/
class CalculatorService implements CalculatorServiceInterface
{
public function add(int $a, int $b): int
{
return $a + $b;
}
}
@RpcService为注解;name="服务名称"。详情看文档
第五步:将服务发布到服务中心
1)添加配置
// config/autoload/services.php
// 新增配置,其他的没有动
return [
// 新增
'enable' => [
'discovery' => true,
'register' => true,
],
'drivers' => [
'consul' => [
'uri' => 'http://192.168.157.128:8500',
'token' => '',
],
],
// 初始化的consumers配置
];
2)发送服务到consul
// 启动后,服务将会自动推送到consul
php bin/hyperf.php start
3)浏览器中查看,发现多了个名叫CalculatorService
的服务。截图如下:
到这里,服务器端配置完毕。
开启的服务不要关闭,接下来进行消费者的操作。
客户端-Hyperf微服务消费者配置
第一步:安装Hyperf
// 配置选择同服务器端配置选择一样
composer create-project hyperf/hyperf-skeleton hyper_client
第二步:服务消费者配置
// config/autoload/server.php
'servers' => [
// servers中,就一个如下配置
[
'name' => 'http',
'type' => Server::SERVER_HTTP,
'host' => '0.0.0.0',
'port' => 9503,
'sock_type' => SWOOLE_SOCK_TCP,
'callbacks' => [
Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'],
],
],
],
第三步:实现消费者
需要与服务器端保持一致
1)定义接口
// app/JsonRpc/CalculatorServiceInterface.php
<?php
namespace App\JsonRpc;
interface CalculatorServiceInterface
{
public function add(int $a, int $b): int;
}
2)实现接口
// app/JsonRpc/CalculatorService.php
<?php
namespace App\JsonRpc;
use Hyperf\RpcClient\AbstractServiceClient;
class CalculatorServiceConsumer extends AbstractServiceClient implements CalculatorServiceInterface
{
/**
* 定义对应服务提供者的服务名称
* @var string
*/
protected $serviceName = 'CalculatorService';
/**
* 定义对应服务提供者的服务协议
* @var string
*/
protected $protocol = 'jsonrpc-http';
public function add(int $a, int $b): int
{
return $this->__request(__FUNCTION__, compact('a', 'b'));
}
}
第四步:定义路由
// config/routes.php
Router::get('/testrpc', 'App\Controller\IndexController@testRpc');
第五步:编写控制器方法
// app/Controller/IndexController.php
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\Utils\ApplicationContext;
use App\JsonRpc\CalculatorServiceInterface;
public function testRpc()
{
$client = ApplicationContext::getContainer()->get(CalculatorServiceInterface::class);
$result = $client->add(1, 2);
return [
'result' => $result,
];
}
第六步:配置services.php
// config/autoload/services.php
// 完整的配置
<?php
declare(strict_types=1);
return [
'consumers' => [
[
// name 需与服务提供者的 name 属性相同
'name' => 'CalculatorService',
// 服务接口名,可选,默认值等于 name 配置的值
'service' => \App\JsonRpc\CalculatorServiceInterface::class,
// 对应容器对象 ID,可选,默认值等于 service 配置的值,用来定义依赖注入的 key
'id' => \App\JsonRpc\CalculatorServiceInterface::class,
// 服务提供者的服务协议,可选,默认值为 jsonrpc-http
// 可选 jsonrpc-http jsonrpc jsonrpc-tcp-length-check
'protocol' => 'jsonrpc-http',
// 负载均衡算法,可选,默认值为 random
'load_balancer' => 'random',
// 这个消费者要从哪个服务中心获取节点信息,如不配置则不会从服务中心获取节点信息
'registry' => [
'protocol' => 'consul',
'address' => 'http://192.168.157.128:8500',
],
// 如果没有指定上面的 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",
],
// 重试次数,默认值为 2,收包超时不进行重试。暂只支持 JsonRpcPoolTransporter
'retry_count' => 2,
// 重试间隔,毫秒
'retry_interval' => 100,
// 当使用 JsonRpcPoolTransporter 时会用到以下配置
'pool' => [
'min_connections' => 1,
'max_connections' => 32,
'connect_timeout' => 10.0,
'wait_timeout' => 3.0,
'heartbeat' => -1,
'max_idle_time' => 60.0,
],
],
]
],
];
第七步:浏览器访问方法
浏览器访问http://192.168.157.128:9503/testrpc
出现{"result":3}
,说明成功^_^
接下来,自己根据这个案例,实现一个Demo的服务/消费吧。
我是温新
每天进步一点点,就一点