Protostuff序列化工具
1. 什么是Protostuff序列化
protostuff是谷歌推出的与语言无关、平台无关的通信协议,一个对象经过protostuff序列化后将变成二进制格式的数据,所以他可读性差,但换来的是占用空间小,速度快。非常适合大量数据的存储,如redis数据存储,rabbitMQ数据存储,都可以利用protostuff提高性能。Google提供了多种语言的实现:java、c++、go和python。
2. Protostuff使用方式
- 如果是基于SpringBoot开发,protostuff的使用非常简单,可以直接引入protostuff开发包。
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>${protostuff.version}</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>${protostuff.version}</version>
</dependency>
- 定义数据模型,这里使用了lombok的@Data注解和@NoArgsConstructor,数据模型必须要有无参构造函数,否则会反序列化异常
@Data
@NoArgsConstructor
public class Student {
private String id;
private String name;
private Integer age;
private Course course;
}
@Data
@NoArgsConstructor
public class Course {
private String id;
private String name;
}
- Protostuff序列化工具类
public class ProtoStuffUtil {
public static <T> byte[] serialize(T obj) {
if (obj == null) {
throw new RuntimeException("Failed to serializer");
} else {
Class<T> clz = (Class<T>) obj.getClass();
Schema<T> schema = RuntimeSchema.getSchema(clz);
LinkedBuffer buffer = LinkedBuffer.allocate(1048576);
byte[] protoStuff;
try {
protoStuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception var8) {
throw new RuntimeException("Failed to serializer");
} finally {
buffer.clear();
}
return protoStuff;
}
}
public static <T> T deserialize(byte[] paramArrayOfByte, Class<T> targetClass) {
if (paramArrayOfByte != null && paramArrayOfByte.length != 0) {
Schema<T> schema = RuntimeSchema.getSchema(targetClass);
T t = schema.newMessage();
ProtostuffIOUtil.mergeFrom(paramArrayOfByte, t, schema);
return t;
} else {
throw new RuntimeException("Failed to deserialize");
}
}
- 使用序列化工具
@SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... strings) throws Exception {
//创建一个Course对象
Course course = new Course();
course.setId(1);
course.setName("数学");
//创建一个Student对象
Student student = new Student();
student.setId(1);
student.setName("周杰伦");
student.setCourse(course);
//使用ProtostuffUtils序列化
byte[] data = ProtoStuffUtil.serialize(student);
System.out.println("序列化后:" + Arrays.toString(data));
Student result = ProtoStuffUtil.deserialize(data, Student.class);
System.out.println("反序列化后:" + result.toString());
}
}
3. 使用注意事项
- protostuff的序列化过程是按照数据模型中的字段顺序依次序列化字段的值,反序列化时会按顺序解析数据然后赋给对应的字段,所以数据模型要遵循以下原则,避免数据错乱:
- 数据模型中的字段一旦使用不可再删除,除非先清除存储的所有序列化数据,但是在线上项目中不推荐这么干
- 数据模型中新增字段必须放在最后面
- 如果是内部对象(如上例中的Course)新增字段,直接在内部对象数据模型中最后一个字段的后面增加新字段即可
- 修改字段应当作新增字段处理
- protobuff只能序列化pojo类,不能直接序列化List 或者Map,如果要序列化list或者map的话,需要用一个wrapper类包装一下