性能最好的序列化反序列化,Protobuf的用法,ProtobufIOUtil工具

原文地址:https://blog.csdn.net/xiaobao5214/article/details/52210152


首先要在pom.xml里添加Protobuf的jar包

  1. <dependency>
  2. <groupId>com.dyuproject.protostuff groupId>
  3. <artifactId>protostuff-core artifactId>
  4. <version>1.0.8 version>
  5. dependency>
  6. <dependency>
  7. <groupId>com.dyuproject.protostuff groupId>
  8. <artifactId>protostuff-runtime artifactId>
  9. <version>1.0.8 version>
  10. dependency>

序列化的实体类User.java(不需要实现Serializable接口)

  1. package com.serialize.entity;
  2. public class User {
  3. private String id;
  4. private String username;
  5. private String password;
  6. public User() {
  7. }
  8. public User(String id, String username, String password) {
  9. this.id = id;
  10. this.username = username;
  11. this.password = password;
  12. }
  13. public String getId() {
  14. return id;
  15. }
  16. public void setId(String id) {
  17. this.id = id;
  18. }
  19. public String getUsername() {
  20. return username;
  21. }
  22. public void setUsername(String username) {
  23. this.username = username;
  24. }
  25. public String getPassword() {
  26. return password;
  27. }
  28. public void setPassword(String password) {
  29. this.password = password;
  30. }
  31. @Override
  32. public String toString() {
  33. return "User [id=" + id + ", username=" + username + ", password="
  34. + password + "]";
  35. }
  36. }
序列化的工具类SerializeUtils.java(使用了泛型方法)

  1. package com.serialize.utils;
  2. import com.dyuproject.protostuff.LinkedBuffer;
  3. import com.dyuproject.protostuff.ProtobufIOUtil;
  4. import com.dyuproject.protostuff.runtime.RuntimeSchema;
  5. public class SerializeUtils{
  6. public static byte[] serialize(T t,Class clazz) {
  7. return ProtobufIOUtil.toByteArray(t, RuntimeSchema.createFrom(clazz),
  8. LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
  9. }
  10. public static T deSerialize(byte[] data,Class clazz) {
  11. RuntimeSchema runtimeSchema = RuntimeSchema.createFrom(clazz);
  12. T t = runtimeSchema.newMessage();
  13. ProtobufIOUtil.mergeFrom(data, t, runtimeSchema);
  14. return t;
  15. }
  16. }
测试主类App.java

  1. package com.serialize;
  2. import com.serialize.entity.User;
  3. import com.serialize.utils.SerializeUtils;
  4. public class App {
  5. public static void main(String[] args) {
  6. User user= new User( "1", "xiaobao", "123456");
  7. System.out.println( "序列化");
  8. byte[] data = SerializeUtils.serialize(user,User.class);
  9. for ( byte b : data) {
  10. System.out.print(b);
  11. }
  12. System.out.println();
  13. System.out.println( "反序列化");
  14. User user2 = SerializeUtils.deSerialize(data,User.class);
  15. System.out.println(user2);
  16. }
  17. }


你可能感兴趣的:(java)