参考:https://www.cnblogs.com/liugh/p/7505533.html
创建Maven项目,pom.xml文件添加如下内容:
<properties>
<protobuf.version>3.6.1</protobuf.version>
<grpc.version>1.18.0</grpc.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${protobuf.version}</version>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
<!-- 编译google protobuffer -->
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
在main目录下新建proto文件夹,并将该文件夹设置为源代码目录(编译时会自动去这个目录下找proto文件),如下图:
在该目录下编写proto文件,这里写各测试的Person.proto,内容如下:
syntax = "proto3"; //标识是protobuffer3 ,默认是2
package protobuffer.proto;
option java_package = "com.heavy.learn.protobuffer";
option java_outer_classname = "PersonPB";
message Person {
sint64 id = 1;
int32 age = 2;
string name=3;
repeated float exam = 4;
bool good =5;
bytes byt = 6;
double d = 7 ;
enum Level {
NORMAL= 0;
GOOD= 1;
BAD = 2;
}
Level level = 8;
map<string,list> map = 9;
message list{
repeated Person ele=1;
}
}
message Family{
repeated Person p =1;
}
使用protobuf下的compile来编译,会生成java代码:
编写测试类,来使用序列化与反序列化
package com.heavy.learn.protobuffer;
import com.google.protobuf.InvalidProtocolBufferException;
import java.util.List;
public class ProtoTest {
public static void main(String[] args) {
PersonPB.Person.Builder person = PersonPB.Person.newBuilder();
person.setAge(12);
person.setId(1);
person.setName("Jacky");
person.setExam(0,2.3f);
person.setExam(1,2.4f);
//设置map
person.putMap("a",null);
PersonPB.Family.Builder fa = PersonPB.Family.newBuilder();
fa.addP(person);
System.out.println(person);
//序列化
PersonPB.Person pinfo = person.build();
byte[] barr = pinfo.toByteArray();
System.out.println(barr.length);
try {
//反序列化
PersonPB.Person p= PersonPB.Person.parseFrom(barr);
System.out.println(p);
//获取list
p.getExamList();
PersonPB.Family f = PersonPB.Family.parseFrom(fa.build().toByteArray());
List<PersonPB.Person> list = f.getPList();
for(PersonPB.Person px : list){
System.out.println(px.getAge());
}
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
}