MessagePack使用研究
MessagePack是一个基于二进制高效的对象序列化类库,可用于跨语言通信。它可以像JSON那样,在许多种语言之间交换结构对象;但是它比JSON更快速也更轻巧。支持Python、Ruby、Java、C/C++等众多语言。比GoogleProtocol Buffers还要快4倍。
代码实现1:
?
package com.newtest;
import java.io.IOException;
import org.msgpack.MessagePack;
import org.msgpack.annotation.Message;
@Message
public class Student {
public int sAge = 0;
public String sName;
public boolean sHasPhone;
public static void main(String[] args) throws IOException {
Student stu = new Student();
stu.sAge = 13;
stu.sName = "programer";
stu.sHasPhone = true;
MessagePack pack = new MessagePack();
// 序列化
byte[] bytes = pack.write(stu);
// 反序列化
Student s = pack.read(bytes, Student.class);
System.out.println("Name: " + s.sName + "\n" + "Age: " + s.sAge + "\n"
+ "HasPhone: " + s.sHasPhone);
}
}
代码实现2:
?
package com.newtest;
?
?import java.io.IOException;
?import org.msgpack.MessagePack;
?import org.msgpack.annotation.Message;
?import org.msgpack.annotation.Optional;
?
?@Message
?public class ServerStudent {
? ? ?public int sAge = 0;
?
? ? ?public String sName;
?
? ? ?public boolean sHasPhone;
?
? ? ?/**
? ? ? * 在Server端相应的Entity里添加需要的属性, 但是为了兼容之前的数据,必须加上注解@Optional
? ? ? * Optional的作用是是否有该字段都不会影响MessagePack的正常解压
? ? ? */
? ? ?@Optional
? ? ?public double sHeight;
?
? ? ?/**
? ? ? * 该类里并没有sHeight字段,可以把它看做已经发出去的产品
? ? ? */
? ? ?@Message
? ? ?static class ClientStudent {
?
? ? ? ? ?public int sAge = 0;
?
? ? ? ? ?public String sName;
?
? ? ? ? ?public boolean sHasPhone;
? ? ?}
?
? ? ?/**
? ? ? * 与目前Server端数据字段相一致的Entity
? ? ? */
? ? ?@Message
? ? ?static class NewClientStudent {
? ? ? ? ?public int sAge = 0;
?
? ? ? ? ?public String sName;
?
? ? ? ? ?public boolean sHasPhone;
?
? ? ? ? ?public double sHeight;
? ? ?}
?
? ? ?public static void main(String[] args) throws IOException {
? ? ? ? ?ClientStudent stu = new ClientStudent();
? ? ? ? ?stu.sAge = 13;
? ? ? ? ?stu.sName = "programer";
? ? ? ? ?stu.sHasPhone = true;
?
? ? ? ? ?NewClientStudent ns = new NewClientStudent();
? ? ? ? ?ns.sAge = 10;
? ? ? ? ?ns.sName = "coder";
? ? ? ? ?ns.sHasPhone = false;
? ? ? ? ?ns.sHeight = 180;
?
? ? ? ? ?MessagePack pack = new MessagePack();
?
? ? ? ? ?// 序列化
? ? ? ? ?byte[] bytes = pack.write(stu);
? ? ? ? ?byte[] nBytes = pack.write(ns);
?
? ? ? ? ?// 反序列化
? ? ? ? ?ServerStudent s = pack.read(bytes, ServerStudent.class);
? ? ? ? ?ServerStudent ss = pack.read(nBytes, ServerStudent.class);
?
? ? ? ? ?System.out.println("之前发布出去的产品: \n" + "Name: " + s.sName + "\n"
? ? ? ? ? ? ? ? ?+ "Age: " + s.sAge + "\n" + "HasPhone: " + s.sHasPhone+"\n\n");
? ? ? ? ?System.out.println("目前的产品: \n" + "Name: " + ss.sName + "\n" + "Age: "
? ? ? ? ? ? ? ? ?+ ss.sAge + "\n" + "HasPhone: " + ss.sHasPhone + "\n"
? ? ? ? ? ? ? ? ?+ "Height: " + ss.sHeight);
? ? ?}
?
?}
需要进入的JARS:见附件
下载链接:
https://github.com/guoyunsky/msgpack-rpc-demo