grpc-java 常用的.proto类型 demo 整理
博主近期在调研 istio,其中涉及需要将自己部门的 rpc 框架切换到 grpc-java 上,因此对 grpc-java 进行了相关调研,这里就对常用的.proto类型进行整理。
.proto文件中消息结构里用于定义字段的标准数据类型如下表所示,后面几列是.proto文件中定义的标准类型编译转换后在编程语言中的类型对照。
下面将对上面提到的 .proto 类型在 Java 代码中的使用给出代码示例
(下面的项目将在上一个示例:grpc-java springboot 同步异步调用 demo 的基础上进一步扩展)
主要包含的复杂结构:数组
,Map
,byte[]
,自定义结构
,枚举类型
首先是 .proto 文件:
syntax = "proto3"; //指定正在使用proto3语法,没有则默认为proto2
option java_package = "grpc.springboot.demo.api";
option java_outer_classname = "ComplexStructService";
package complex.struct.service;
service ComplexStruct {
//定义一个rpc方法,请求跟相应的内容,均为自定义类型
rpc invoker (ComplexStructRequest) returns (ComplexStructResponse) {}
}
//定义请求体
message ComplexStructRequest {
//定义字符串类型
string msg = 1;
//定义浮点类型
double num = 2;
//定义long类型
sint64 longNum = 3;
//定义int类型
sint32 shortNum = 4;
//定义boolean类型
bool check = 5;
//定义int型数组
repeated sint32 shortNumArray = 6;
//定义字符串数组
repeated string messageArray = 7;
//定义map结构,k-v均为字符串
map<string, string> testMap = 8;
//定义枚举类型
enumType enumTypeNum = 9;
//定义字节数组
bytes data = 10;
}
//定义响应类型
message ComplexStructResponse {
//包含了自定义Result
Result result = 1;
//自定义Result的数组
repeated Result resultList = 2;
//自定义Result的map
map<string, Result> resultMap = 3;
}
message Result {
sint64 id = 1;
string message = 2;
}
//枚举类型
enum enumType {
ENUM_TYPE_0 = 0;
ENUM_TYPE_1 = 1;
ENUM_TYPE_2 = 2;
ENUM_TYPE_3 = 3;
}
对于 List 或者是 Map,代码添加时,都可以通过 addAllXxxx
整个 List/Map 对象赋值,或者通过 addXxx
的方法,依次进行赋值。具体见客户端与服务端代码。
客户端代码:
@RestController
public class ComplexStructController {
private static final Logger logger = LoggerFactory.getLogger(ComplexStructController.class);
private GrpcClient client;
@Autowired
public ComplexStructController(GrpcClient client) {
this.client = client;
}
// 这里构建了一个请求,用于触发客户端调用服务端
@GetMapping("/complex/struct/hello")
public String hello() {
List<String> allMessageArray = new ArrayList<>();
allMessageArray.add("string1");
allMessageArray.add("string2");
allMessageArray.add("string3");
Map<String, String> testMap = new HashMap<>();
testMap.put("key1", "value1");
testMap.put("key2", "value2");
String string = "hello world";
byte[] bytes = string.getBytes();
ComplexStructService.ComplexStructRequest request = ComplexStructService.ComplexStructRequest
.newBuilder()
// 添加基础的数据类型