MessagePack: MessagePack入门

翟缪文
2023-12-01

http://blog.csdn.net/sunning9001/article/details/50420290


MessagePack介绍:

MessagePack is an efficient binary serialization format.It lets you exchange data among multiple languages like JSON. But it's faster and smaller.
Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves.


支持语言:

MessagePack is supported by over 50 programming languages and environments.

Smalltalk        ActionScript3    PHP              Lua              Rust             Elixir           Scheme           C++11            Go               mruby            Elixir           Rails            Python           Julia            Clojure          Clojure          SML              C                Dart             HHVM             F#               Jackson-dataformaSwift            Objective-C      Node             Haskell          Pascal           Delphi           Qt               Go               Shell            C#               Elixir           Scala            Python/Twisted   J                Swift            Nim              C                Rust             Nim              Crystal          JavaScript       UNIX             PHP              Swift            C#               

1-使用@Message 可以标记被序列化的类。类中所有成员都会被序列化。

  1. @Message  
  2. public class SerializeObject  
  3. {  
  4.     private int i;  
  5.     private String str;  
  6.     public short s;  
  7.     public long l;  
  8.     public SerializeObject(int i, String str, short s, long l) {  
  9.         super();  
  10.         this.i = i;  
  11.         this.str = str;  
  12.         this.s = s;  
  13.         this.l = l;  
  14.     }  
  15. }  
@Message
public class SerializeObject
{
	private int i;
	private String str;
	public short s;
	public long l;
	public SerializeObject(int i, String str, short s, long l) {
		super();
		this.i = i;
		this.str = str;
		this.s = s;
		this.l = l;
	}
}


  1. MessagePack msgpack = new MessagePack();  
  2. SerializeObject src = new SerializeObject(1"str", (short23);  
  3. // Serialize  
  4. byte[] bytes = msgpack.write(src);  
  5.   
  6. // Deserialize  
  7. SerializeObject dst = msgpack.read(bytes, SerializeObject.class);  
  8. System.out.println(dst.toString());  
		MessagePack msgpack = new MessagePack();
		SerializeObject src = new SerializeObject(1, "str", (short) 2, 3);
		// Serialize
		byte[] bytes = msgpack.write(src);
		
		// Deserialize
		SerializeObject dst = msgpack.read(bytes, SerializeObject.class);
		System.out.println(dst.toString());

2 -使用@optional 注解可以用于版本升级

  1. @Message  
  2. public class NewSerializeObject extends SerializeObject {  
  3.     @Optional  
  4.     private String nstr = "";  
  5.   
  6.     public String getNstr() {  
  7.         return nstr;  
  8.     }  
  9.   
  10.     public void setNstr(String nstr) {  
  11.         this.nstr = nstr;  
  12.     }  
  13.   
  14.     @Override  
  15.     public String toString() {  
  16.         return "NewSerializeObject [nstr=" + nstr + "]";  
  17.     }  
  18. }  
@Message
public class NewSerializeObject extends SerializeObject {
	@Optional
	private String nstr = "";

	public String getNstr() {
		return nstr;
	}

	public void setNstr(String nstr) {
		this.nstr = nstr;
	}

	@Override
	public String toString() {
		return "NewSerializeObject [nstr=" + nstr + "]";
	}
}
  1. MessagePack msgpack = new MessagePack();  
  2. SerializeObject src = new SerializeObject(1"str", (short23);  
  3. // Serialize  
  4. byte[] bytes = msgpack.write(src);  
  5.   
  6. // Deserialize  
  7. SerializeObject dst = msgpack.read(bytes, SerializeObject.class);  
  8. System.out.println(dst.toString());  
  9. //使用@optional注解,来升级序列化对象  
  10. NewSerializeObject newDst = msgpack.read(bytes, NewSerializeObject.class);  
  11. System.out.println(newDst.toString());  
		MessagePack msgpack = new MessagePack();
		SerializeObject src = new SerializeObject(1, "str", (short) 2, 3);
		// Serialize
		byte[] bytes = msgpack.write(src);
		
		// Deserialize
		SerializeObject dst = msgpack.read(bytes, SerializeObject.class);
		System.out.println(dst.toString());
		//使用@optional注解,来升级序列化对象
		NewSerializeObject newDst = msgpack.read(bytes, NewSerializeObject.class);
		System.out.println(newDst.toString());
		
	
3- 序列化list数组


  1.   MessagePack msgpack = new MessagePack();  
  2.   
  3.    // Create templates for serializing/deserializing List and Map objects  
  4. //使用template来序列化List数组。  
  5.    Template<List<String>> listTmpl = Templates.tList(Templates.TString);  
  6.   
  7.   
  8.    //  
  9.    // Serialization  
  10.    //  
  11.   
  12.    ByteArrayOutputStream out = new ByteArrayOutputStream();  
  13.    Packer packer = msgpack.createPacker(out);  
  14.   
  15.    // Serialize List object  
  16.    List<String> list = new ArrayList<String>();  
  17.    list.add("msgpack");  
  18.    list.add("for");  
  19.    list.add("java");  
  20.    packer.write(list); // List object  
  21.   
  22.    //  
  23.    // Deserialization  
  24.    //  
  25.    byte[] bytes = out.toByteArray();  
  26.    ByteArrayInputStream in = new ByteArrayInputStream(bytes);  
  27.    Unpacker unpacker = msgpack.createUnpacker(in);  
  28.    // to List object  
  29.    List<String> dstList = unpacker.read(listTmpl);  
  30.           System.out.println(dstList);  
	       MessagePack msgpack = new MessagePack();

	        // Create templates for serializing/deserializing List and Map objects
		    //使用template来序列化List数组。
	        Template<List<String>> listTmpl = Templates.tList(Templates.TString);


	        //
	        // Serialization
	        //

	        ByteArrayOutputStream out = new ByteArrayOutputStream();
	        Packer packer = msgpack.createPacker(out);

	        // Serialize List object
	        List<String> list = new ArrayList<String>();
	        list.add("msgpack");
	        list.add("for");
	        list.add("java");
	        packer.write(list); // List object

	        //
	        // Deserialization
	        //
	        byte[] bytes = out.toByteArray();
	        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
	        Unpacker unpacker = msgpack.createUnpacker(in);
	        // to List object
	        List<String> dstList = unpacker.read(listTmpl);
                System.out.println(dstList);
	    


4- 序列化map对象

  1. MessagePack msgpack = new MessagePack();  
  2.   
  3.     // Create templates for serializing/deserializing List and Map objects  
  4.  //使用template来序列化map对象  
  5. Template<Map<String, String>> mapTmpl = Templates.tMap(Templates.tString(), Templates.tString());  
  6.   
  7.   
  8.     //  
  9.     // Serialization  
  10.     //  
  11.   
  12.     ByteArrayOutputStream out = new ByteArrayOutputStream();  
  13.     Packer packer = msgpack.createPacker(out);  
  14.   
  15.     // Serialize Map object  
  16.     Map<String, String> map = new HashMap<String, String>();  
  17.     map.put("sadayuki""furuhashi");  
  18.     map.put("muga""nishizawa");  
  19.     packer.write(map); // Map object  
  20.   
  21.     //  
  22.     // Deserialization  
  23.     //  
  24.     byte[] bytes = out.toByteArray();  
  25.     ByteArrayInputStream in = new ByteArrayInputStream(bytes);  
  26.     Unpacker unpacker = msgpack.createUnpacker(in);  
  27.     // to List object  
  28.     // to Map object  
  29.     Map<String, String> dstMap = unpacker.read(mapTmpl);  
  30.     System.out.println(dstMap);  
		   MessagePack msgpack = new MessagePack();

	        // Create templates for serializing/deserializing List and Map objects
		    //使用template来序列化map对象
		   Template<Map<String, String>> mapTmpl = Templates.tMap(Templates.tString(), Templates.tString());


	        //
	        // Serialization
	        //

	        ByteArrayOutputStream out = new ByteArrayOutputStream();
	        Packer packer = msgpack.createPacker(out);

	        // Serialize Map object
	        Map<String, String> map = new HashMap<String, String>();
	        map.put("sadayuki", "furuhashi");
	        map.put("muga", "nishizawa");
	        packer.write(map); // Map object

	        //
	        // Deserialization
	        //
	        byte[] bytes = out.toByteArray();
	        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
	        Unpacker unpacker = msgpack.createUnpacker(in);
	        // to List object
	        // to Map object
	        Map<String, String> dstMap = unpacker.read(mapTmpl);
	        System.out.println(dstMap);


5 -MessagePack 不支持对Object对象的序列化,但是jackson-dataformat-msgpack 提供对messagepack格式的序列化和反序列化。

This Jackson extension library handles reading and writing of data encoded in MessagePack data format.

  1. public class ExamplePojo {  
  2.     private String name;  
  3.     public ExamplePojo(String name) {  
  4.         super();  
  5.         this.name = name;  
  6.     }  
  7.     public String getName() {  
  8.         return name;  
  9.     }  
  10.     public void setName(String name) {  
  11.         this.name = name;  
  12.     }  
  13.     public ExamplePojo() {  
  14.     }  
  15. }  
public class ExamplePojo {
	private String name;
	public ExamplePojo(String name) {
		super();
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public ExamplePojo() {
	}
}
  1.               ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());  
  2. ExamplePojo orig = new ExamplePojo("komamitsu");  
  3. byte[] bytes = objectMapper.writeValueAsBytes(orig);  
  4.   
  5.   
  6. ExamplePojo value = objectMapper.readValue(bytes, ExamplePojo.class);  
  7. System.out.println(value.getName()); // => komamitsu  
                ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
		ExamplePojo orig = new ExamplePojo("komamitsu");
		byte[] bytes = objectMapper.writeValueAsBytes(orig);
		
		
		ExamplePojo value = objectMapper.readValue(bytes, ExamplePojo.class);
		System.out.println(value.getName()); // => komamitsu


这让人情何以堪,MessagePack 支持力度果然不行啊。
 类似资料: