特点
使用
编写流程
先编译要序列的实体属性到Protot文件中
-
User.proto文件
//生成我们的java地址
option java_package="cn.popdemo.protobuf";
//生成java文件名
option java_outer_classname="UserSerializer";
//对应其序列化类的属性
//每个属性都有个人的ID
message User{
required int64 id = 1;
required string userName = 2;
required string userPassword = 3;
required int64 money = 4;
}
-
- 使用Google的工具包对其进行编译为java文件
- > 生成批处理结合工具包生成java文件
>
> protoc ./User.Proto --java_out=./
>
> pause
- 将生成后的java文件放置到项目中的Protobuf文件中
- ![img](http://m.qpic.cn/psc?/V12figq01webP8/Af1yGqSdppVqA7I0*cpgDF1YeBJTQhI6D0h0EG5HfpVuVNcnUQWdGOeH6kb80Vd9SK5CbMdUdGlLnsLSZxfg8f1eipjWCVL2dNjKVuvH0tk!/b&bo=QALBAQAAAAADF7A!&rf=viewer_4)
- 添加Protobuf依赖
- > ```
> <!-- protobuf -->
> <dependency>
> <groupId>com.google.protobuf</groupId>
> <artifactId>protobuf-java</artifactId>
> <version>3.7.1</version>
> </dependency>
>
- 编写序列化过程(也就是↓)
- 序列化过程
- > ```java
public static void main(String[] args) throws InvalidProtocolBufferException {
//接受序列化后的byte字节
//并进行输出
byte[] bt = serialize();
System.out.println(Arrays.toString(bt));
//接收到byte并进行反序列化到实体
UserSerializer.User user = Notserialize(bt);
System.out.println(user.getId());
System.out.println(user.getUserName());
System.out.println(user.getUserPassword());
System.out.println(user.getMoney());
}
//protobuf序列化
private static byte[] serialize(){
//构造序列化器builder来构造我们的User
Builder builder = UserSerializer.User.newBuilder();
//构造User
builder.setId(1).setUserName("PopDemo").setUserPassword("123123").setMoney(1629);
//生成序列实体
UserSerializer.User user = builder.build();
//进行序列化并返回byte(字节)
byte[] bt = user.toByteArray();
return bt;
}
//protobuf反序列化
private static UserSerializer.User Notserialize(byte[] bt) throws InvalidProtocolBufferException {
//使用返回的byte进行反序列化到User
UserSerializer.User user = UserSerializer.User.parseFrom(bt);
return user;
}