protobuf官方包下载:https://github.com/protocolbuffers/protobuf/releases/tag/v3.11.1
1、Idea中安装protobuf插件,重启Idea
2、idea中新建maven项目protobuf-demo
3、pom.xml中添加如下依赖
UTF-8 com.google.protobuf protobuf-java 3.6.1 junit junit 4.13 test kr.motd.maven os-maven-plugin 1.4.1.Final org.xolstice.maven.plugins protobuf-maven-plugin 0.5.0 com.google.protobuf:protoc:3.1.0:exe:${os.detected.classifier} grpc-java compile compile-custom
4、在idea中编写proto文件,目录结构如下
内容如下:
syntax = "proto3";
option java_package = "com.black.model";
option java_outer_classname = "PersonModel";
message Person {
int32 id = 1;
string name = 2;
string email = 3;
}
5、生成java
6、测试代码
public class PersonModelTest {
public static void main(String[] args) throws InvalidProtocolBufferException {
PersonModel.Person.Builder builder= PersonModel.Person.newBuilder();
builder.setId(1);
builder.setEmail("lee@sunvalley.com.cn");
builder.setName("lee");
PersonModel.Person person= builder.build();
System.out.print("====before===="+person);
System.out.println("==================");
for(Byte b:person.toByteArray()){
System.out.print(b);
}
System.out.println("==================");
byte[] byteArray= person.toByteArray();
PersonModel.Person p2 = PersonModel.Person.parseFrom(byteArray);
System.out.println("=========反序列化生成对象,转换之后==========");
System.out.println(p2.getId()+","+p2.getEmail()+","+p2.getName());
}
}