1、maven
<!-- https://mvnrepository.com/artifact/org.msgpack/msgpack --> <dependency> <groupId>org.msgpack</groupId> <artifactId>msgpack</artifactId> <version>0.6.7</version> </dependency>
2、被序列化的类(com.utils.User.java)
/** * <p>Title: </p> * <p>Description: </p> * * @Author * @CreateTime */ //@Message public class User { private Long id; private String provinceName; private Integer age; private Date createdTime; //这个默认构造函数必须要有,不然用Msgpack序列化时会报错 public User() { } public User(Long id, String provinceName, Integer age, Date createdTime) { this.id = id; this.provinceName = provinceName; this.age = age; this.createdTime = createdTime; } public User buildUserId(Long id) { this.id = id; return this; } public User buildAge(Integer age) { this.age = age; return this; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getProvinceName() { return provinceName; } public void setProvinceName(String provinceName) { this.provinceName = provinceName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } }
3.测试实例
public static void main(String[] args) throws Exception { MessagePack msgpack = new MessagePack(); try { User user = new User(1001L, "山西", 23, new Date()); // User user = new User(); // user.buildAge(12); msgpack.register(User.class);//与 @Message注解用其一即可 byte[] serial = msgpack.write(user); // User user2 = msgpack.read(serial, User.class);//可以 User user2 = msgpack.read(serial, user);//可以 System.out.println(user2.getAge());//12 } catch (IOException e) { e.printStackTrace(); } // Exception in thread "main" org.msgpack.MessageTypeException: // Cannot find template for class com.weather.weatherexpert.common.utils.MsgpackUtil$User class. // Try to add @Message annotation to the class or call MessagePack.register(Type). }
报错:
1.User类的默认构造函数必须要有,不然用Msgpack序列化时会报错:no such constructor: com.utils.User
2.User类上需添加@Message或使用msgpack.register(User.class),否则会报错:Cannot find template for class com.utils.User class. Try to add @Message annotation to the class or call MessagePack.register(Type).
参考:https://blog.csdn.net/u010002184/article/details/86546133