您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
jsonrpc客户端(hyperf实现)
发布时间:2022-10-21 22:04:39编辑:雪饮阅读()
Jsonrpc客户端调用入口
用户请求到192.168.31.80
public function json_rpc_test(){
$client = ApplicationContext::getContainer()->get(UserServiceInterface::class);
$result = $client->createUser("snowDrink",1);
return $result;
}
入口路由:
Router::addRoute(['GET', 'POST', 'HEAD'], '/json_rpc_test', 'App\Controller\IndexController@json_rpc_test');
消费者接口(提供者接口)
192.168.31.173做为服务端需要将其做为提供者接口,192.168.31.80做为客户端将其做为消费者接口
<?php
namespace App\JsonRpc;
interface UserServiceInterface{
public function createUser(string $name, int $gender);
}
?>
消费者(提供者)实例
同其接口一样,提供方与消费方都要有该实现
<?php
declare(strict_types=1);
namespace App\JsonRpc;
use Hyperf\RpcServer\Annotation\RpcService;
/**
* Class UserService
* @package App\JsonRpc
* @RpcService(name="UserService", protocol="jsonrpc-http", server="jsonrpc-http")
*/
class UserService implements UserServiceInterface
{
//public $name="UserService";
/**
* @param string $name
* @param string $gender
* @return string
*/
public function createUser(string $name, int $gender)
{
exec("ifconfig", $out, $stats);
$out_muti_row_str="";
foreach($out as $key=>$val){
$out_muti_row_str.=$val."\r\n";
}
$response="create info:\r\n".$out_muti_row_str."\r\n";
$response.="\r\nname:".$name.",gender:".$gender."\r\n";
return $response;
}
}
配置消费者的提供节点
192.168.31.80做为客户端需要配置自己的消费者所消费的服务来自192.168.31.173服务节点(也可配置为本地,则本地自己也实现服务提供者),config/autoload/services.php:
<?php
return [
'consumers' => [
[
// name 需与服务提供者的 name 属性相同
'name' => 'UserService',
// 服务接口名,可选,默认值等于 name 配置的值,如果 name 直接定义为接口类则可忽略此行配置,如 name 为字符串则需要配置 service 对应到接口类
'service' => \App\JsonRpc\UserServiceInterface::class,
// 对应容器对象 ID,可选,默认值等于 service 配置的值,用来定义依赖注入的 key
'id' => \App\JsonRpc\UserServiceInterface::class,
// 服务提供者的服务协议,可选,默认值为 jsonrpc-http
// 可选 jsonrpc-http jsonrpc jsonrpc-tcp-length-check
'protocol' => 'jsonrpc-http',
// 负载均衡算法,可选,默认值为 random
'load_balancer' => 'random',
// 这个消费者要从哪个服务中心获取节点信息,如不配置则不会从服务中心获取节点信息
/* 'registry' => [
'protocol' => 'consul',
'address' => 'http://127.0.0.1:8500',
],*/
// 如果没有指定上面的 registry 配置,即为直接对指定的节点进行消费,通过下面的 nodes 参数来配置服务提供者的节点信息
'nodes' => [
['host' => '192.168.31.173', 'port' => 9600],
],
// 配置项,会影响到 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,
],
],
]
],
];
关键字词:jsonrpc,客户端,hyperf,实现