介绍

在很多地方都需要用到序列化, 比如在使用redis缓存对象时, 一般情况是实现java Serializable接口. 简单介绍下在慕课网学习到的一个新的序列化工具 —— protostuff.
在学习中介绍使用该工具可以大大减少对象序列化后字节所占空间, 并提高序列化时间等.
1.慕课网课程地址
2.序列化相关工具比较

引入依赖

  1. <!-- protostuff 序列化工具 -->
  2. <dependency>
  3. <groupId>com.dyuproject.protostuff</groupId>
  4. <artifactId>protostuff-core</artifactId>
  5. <version>1.1.3</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.dyuproject.protostuff</groupId>
  9. <artifactId>protostuff-runtime</artifactId>
  10. <version>1.1.3</version>
  11. </dependency>

相关使用

  1. import com.dyuproject.protostuff.LinkedBuffer;
  2. import com.dyuproject.protostuff.ProtostuffIOUtil;
  3. import com.dyuproject.protostuff.runtime.RuntimeSchema;
  4. /**
  5. * @author liuzhihang
  6. * @date 2018/4/18 15:04
  7. */
  8. public class ProtostuffUtil {
  9. public static <T> byte[] serialize(T t, Class<T> cls) {
  10. RuntimeSchema<T> schema = RuntimeSchema.createFrom(cls);
  11. return ProtostuffIOUtil.toByteArray(t, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
  12. }
  13. public static <T> T unSerialize(byte[] bytes, Class<T> cls) {
  14. RuntimeSchema<T> schema = RuntimeSchema.createFrom(cls);
  15. T message = schema.newMessage();
  16. ProtostuffIOUtil.mergeFrom(bytes, message, schema);
  17. return message;
  18. }
  19. }

测试

  1. import lombok.Data;
  2. /**
  3. * @author liuzhihang
  4. * @date 2018/4/17 19:01
  5. */
  6. @Data
  7. public class User {
  8. private String id;
  9. private String userName;
  10. }
  11. import com.alibaba.fastjson.JSON;
  12. /**
  13. * @author liuzhihang
  14. * @date 2018/4/17 19:02
  15. */
  16. public class ProtostuffTest {
  17. public static void main(String[] args) {
  18. User user = new User();
  19. user.setId("test0001");
  20. user.setUserName("测试用户0001");
  21. System.out.println(JSON.toJSONString(user));
  22. byte[] serialize = ProtostuffUtil.serialize(user, User.class);
  23. User unSerialize = ProtostuffUtil.unSerialize(serialize, User.class);
  24. System.err.println(JSON.toJSONString(unSerialize));
  25. }
  26. }
  27. 结果:
  28. {"id":"test0001","userName":"测试用户0001"}
  29. {"id":"test0001","userName":"测试用户0001"}