Hyperf jsonrpc 服务的搭建
Posted 波波波波波波
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hyperf jsonrpc 服务的搭建相关的知识,希望对你有一定的参考价值。
JSON-RPC,是一个无状态且轻量级的远程过程调用(RPC)传送协议,其传递内容透过 JSON 为主。
我们需要布置两台服务,一台Provider提供服务,另外一台Consumer消费服务
准备工作
1、所需类库
composer require hyperf/json-rpc
composer require hyperf/rpc-server
composer require hyperf/rpc-client
composer require hyperf/consul
composer require hyperf/service-governance
2、工具
Mac环境下
安装consul brew install consul
启动consul brew services start consul
3、Provider的配置
1、服务提供类
<?php namespace AppRpc; use HyperfRpcServerAnnotationRpcService; /** * @RpcService(name="CalculatorService",protocol="jsonrpc-http",server="jsonrpc-http") */ class CalculatorService implements CalculatorServiceInterface { public function add(int $a, int $b): int { return $a + $b; }
public function minus(int $a, int $b): int { return $a - $b; } }
2、接口类
<?php namespace AppRpc; interface CalculatorServiceInterface { public function add(int $a, int $b): int; public function minus(int $a, int $b): int; }
3、配置文件 service.php
‘servers‘ => [ ... [ ‘name‘ => ‘jsonrpc-http‘, ‘type‘ => Server::SERVER_HTTP, ‘host‘ => ‘0.0.0.0‘, ‘port‘ => 9802, ‘sock_type‘ => SWOOLE_SOCK_TCP, ‘callbacks‘ => [ SwooleEvent::ON_REQUEST => [HyperfJsonRpcHttpServer::class, ‘onRequest‘], ], ], ],
3、Consumer 的配置
1、接口类
<?php
namespace AppRpc;
interface CalculatorServiceInterface
{
public function add(int $a, int $b): int;
public function minus(int $a, int $b): int;
}
2、配置文件 services.php
return [
‘consumers‘ => [
[
‘name‘ => ‘CalculatorService‘,
‘service‘ => AppRpcCalculatorServiceInterface::class,
‘nodes‘ => [
[
‘host‘ => ‘0.0.0.0‘,
‘port‘ => 9802
],
],
],
],
];
3、调用
<?php namespace AppController; use AppRpcCalculatorServiceInterface; use HyperfDiAnnotationInject; use HyperfHttpServerAnnotationAutoController; /** * @AutoController() */ class IndexController extends AbstractController { /** * @Inject() * @var CalculatorServiceInterface */ private $calculatorService; public function rpc() { return $this->calculatorService->minus(10,2); } }
4、使用consul
如果需要使用 consul来管理服务,则需要做如下操作
1).修改Provider具体的服务类,注解添加属性 publishTo
/** * @RpcService(name="CalculatorService",protocol="jsonrpc-http",server="jsonrpc-http",publishTo="consul")
*/
2).Provider服务发布
php bin/hyperf.php vendor:publish hyperf/consul
执行完毕后会形成一个配置文件 consul.php
3).Conusmer修改配置
return [ ‘consumers‘ => [ [ ‘name‘ => ‘CalculatorService‘, ‘service‘ => AppRpcCalculatorServiceInterface::class,
registry‘ => [
‘protocol‘ => ‘consul‘,
‘address‘ => ‘http://127.0.0.1:8500‘,//对应Provider 中 consul.php配置项 ]
],
],
];
4)重新启动Provider和Consumer
以上是关于Hyperf jsonrpc 服务的搭建的主要内容,如果未能解决你的问题,请参考以下文章