proto
syntax = "proto2";
package com.seeyou.grpcdemo;
message Animal {
optional string name = 1;
}
gradle 依赖
根目录 gradle
dependencies {
...
classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.17"
}
项目 gradle
plugins {
...
id 'com.google.protobuf'
}
...
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.19.2"
}
plugins {
grpc {
artifact = 'io.grpc:protoc-gen-grpc-java:1.47.0'
}
}
generateProtoTasks {
all().each { task ->
task.builtins {
java { option '' }
}
task.plugins {
grpc { option '' }
}
}
}
}
dependencies {
...
implementation 'io.grpc:grpc-okhttp:1.47.0'
implementation 'io.grpc:grpc-protobuf:1.47.0'
implementation 'io.grpc:grpc-stub:1.47.0'
compileOnly 'org.apache.tomcat:annotations-api:6.0.53'
implementation 'com.google.protobuf:protobuf-java-util:3.19.2'
}
java序列化、反序列化 代码
TestService.Animal dog = TestService.Animal.newBuilder().setName("Dog").build();
TestService.Animal.Builder dogBuild = TestService.Animal.newBuilder().setName("Dog");
try {
String s = TextFormat.printer().printToString(dog);//序列化 文本
String print = JsonFormat.printer().print(dog);//序列话json
TextFormat.merge(s, dogBuild); //text反序列化
JsonFormat.parser().merge(print, dogBuild); //json反序列化
} catch (Exception e) {
e.printStackTrace();
}