MessagePack序列化物件的例項
阿新 • • 發佈:2021-10-09
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