messagePack编解码

首先引入javassist-3.20.0-GA.jar与msgpack-0.6.12.jar两个包,然后就可以使用.

 package com.ming.netty.code;

 import java.io.Serializable;
import java.nio.ByteBuffer; /**
* 一个普通学生类
* @author mingge
*
*/
public class Student implements Serializable{
private static final long serialVersionUID = 1L; private String stuName; public String getStuName() {
return stuName;
} public void setStuName(String stuName) {
this.stuName = stuName;
} public byte[] codeC(){
ByteBuffer buffer=ByteBuffer.allocate(1024);
byte[] value=this.getStuName().getBytes();
buffer.putInt(value.length);
buffer.put(value);
buffer.flip();
value=null;
byte[] result=new byte[buffer.remaining()];
buffer.get(result);
return result;
} }
 package com.ming.netty.code;

 import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List; import org.msgpack.MessagePack;
import org.msgpack.template.Templates; public class TestMsgPack { public static void main(String[] args) throws Exception{
List<String> list=new ArrayList<>();
list.add("a");
list.add("b");
list.add("c"); ByteArrayOutputStream bos=new ByteArrayOutputStream();
ObjectOutputStream os=new ObjectOutputStream(bos);
os.writeObject(list);
os.flush();
os.close();
byte[] b=bos.toByteArray();
System.out.println("list的jdk序列化长度:"+b.length); MessagePack msgpack=new MessagePack();
byte[] bytes=msgpack.write(list);//序列化编码
System.out.println("list的msgpack序列化长度:"+bytes.length); List<String> dst=msgpack.read(bytes,Templates.tList(Templates.TString));//反序列化
System.out.println("反序列化获取的值:"+dst.get(0)); Teacher t=new Teacher();
t.setNo(1);
t.setName("张三");
t.setSex("男");
MessagePack msgpack1=new MessagePack();
byte[] bytes1=MessagePack.pack(t);//序列化编码
System.out.println("teacher序列化长度:"+bytes1.length); Teacher t1=msgpack1.read(bytes1, Teacher.class);
System.out.println("t1的值:"+t1.getName());
}
}

运行结果集:

list的jdk序列化长度:70
list的msgpack序列化长度:7
反序列化获取的值:a
teacher序列化长度:13
t1的值:张三

显然msgpack的序列化比jdk序列化要好一点.

上一篇:不愿看到Java开发者再做的10件事


下一篇:ajax请求导致status为canceled(无任何回调数据)的原因