1.maven
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.3.0</version>
</dependency>
2.编辑person_entity.proto文件
syntax = "proto2";
option java_package = "com.boomsecret.protobuf.proto";
option java_outer_classname = "PersonEntity";
message person_entity {
required int32 id = 1; // ID
required string name = 2; // 姓名
optional string email = 3; // 邮箱
}
3.下载protoc.exe,并生成.java文件
https://github.com/google/protobuf/releases
protoc.exe --java_out=.\..\src\main\java .\proto\person_entity.proto
(com.boomsecret.protobuf.proto.PersonEntity.java)
4.小李子
public class ProtoBufDemo {
public static void main(String[] args) {
PersonEntity.person_entity.Builder builder = PersonEntity.person_entity.newBuilder();
builder.setId(100);
builder.setName("jack");
builder.setEmail("jack@email.com");
person_entity personEntity = builder.build();
System.out.println(personEntity.toString());
byte[] bytes = personEntity.toByteArray();
for (byte index : bytes) {
System.out.print(index);
}
System.out.println();
try {
person_entity parsePersonEntity = person_entity.parseFrom(bytes);
System.out.println(parsePersonEntity);
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
}
5.总结
protobuf比xml和json效率高很多,具体可以去了解下,这里不做详细介绍。
网友评论