首先引入javassist-3.20.0-GA.jar与msgpack-0.6.12.jar两个包,然后就可以使用.
1 package com.ming.netty.code; 2 3 import java.io.Serializable; 4 import java.nio.ByteBuffer; 5 6 7 /** 8 * 一个普通学生类 9 * @author mingge10 *11 */12 public class Student implements Serializable{13 private static final long serialVersionUID = 1L;14 15 private String stuName;16 17 18 public String getStuName() {19 return stuName;20 }21 22 public void setStuName(String stuName) {23 this.stuName = stuName;24 }25 26 public byte[] codeC(){27 ByteBuffer buffer=ByteBuffer.allocate(1024);28 byte[] value=this.getStuName().getBytes();29 buffer.putInt(value.length);30 buffer.put(value);31 buffer.flip();32 value=null;33 byte[] result=new byte[buffer.remaining()];34 buffer.get(result);35 return result;36 }37 38 }
1 package com.ming.netty.code; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.ObjectOutputStream; 5 import java.util.ArrayList; 6 import java.util.List; 7 8 import org.msgpack.MessagePack; 9 import org.msgpack.template.Templates;10 11 public class TestMsgPack {12 13 public static void main(String[] args) throws Exception{14 Listlist=new ArrayList<>();15 list.add("a");16 list.add("b");17 list.add("c");18 19 ByteArrayOutputStream bos=new ByteArrayOutputStream();20 ObjectOutputStream os=new ObjectOutputStream(bos);21 os.writeObject(list);22 os.flush();23 os.close();24 byte[] b=bos.toByteArray();25 System.out.println("list的jdk序列化长度:"+b.length);26 27 MessagePack msgpack=new MessagePack();28 byte[] bytes=msgpack.write(list);//序列化编码29 System.out.println("list的msgpack序列化长度:"+bytes.length);30 31 List dst=msgpack.read(bytes,Templates.tList(Templates.TString));//反序列化32 System.out.println("反序列化获取的值:"+dst.get(0));33 34 Teacher t=new Teacher();35 t.setNo(1);36 t.setName("张三");37 t.setSex("男");38 MessagePack msgpack1=new MessagePack();39 byte[] bytes1=MessagePack.pack(t);//序列化编码40 System.out.println("teacher序列化长度:"+bytes1.length);41 42 43 44 Teacher t1=msgpack1.read(bytes1, Teacher.class);45 System.out.println("t1的值:"+t1.getName());46 }47 }
运行结果集:
list的jdk序列化长度:70list的msgpack序列化长度:7反序列化获取的值:ateacher序列化长度:13t1的值:张三
显然msgpack的序列化比jdk序列化要好一点.