The Protobuf of Java serialization

Source: Internet
Author: User

Tag:java    serialization    protostuff   

package com.book.core.test;import java.math.bigdecimal;import java.util.arraylist;import  java.util.list;import com.book.core.model.type;import com.book.core.serializable.serializationutil; Import com.dyuproject.protostuff.linkedbuffer;import com.dyuproject.protostuff.protobufioutil;import  com.dyuproject.protostuff.ProtostuffIOUtil;import com.dyuproject.protostuff.Schema;import  Com.dyuproject.protostuff.runtime.runtimeschema;/** * protostuff Test  *  @author  liweihan  * */public class testprotostuff {public static void main (String[]  args)  throws Exception {/** * ***********  Test 1 :  The original serialized object  **  *///serialization System.out.println (" =========  Serialization start:"  ); Schema<type> schema = runtimeschema.getschema (Type.class); Type type = new type (); Type.setcityid (1); Type.setprice (New&nbsP BigDecimal (+)); Type.settypename ("Chao Han"); Linkedbuffer buffer = linkedbuffer.allocate (1024x768);byte[] data =  Protobufioutil.tobytearray (Type, schema, buffer); System.out.println ("Serialized Size:"  + data.length +  "  byte  !"); /deserialization System.out.println (" =========  start of deserialization:"  ); Type type2 = new type (); Protobufioutil.mergefrom (Data, type2, schema); System.out.println (" ======  results after deserialization: Cityid:"  + type2.getcityid ()  +  "&NBSP; TypeName: " + type2.gettypename ()  + "  , price: " + type2.getprice ());/**  * ************  test 2 : Serializing collections individually  ************** */Type t1 = new  Type (); T1.setid (1); T1.setcityid (1); T1.setprice (New bigdecimal (1)); T1.settypename ("Testhan"); List<type> list1 = new arraylist<type> (); List1.add (t1); List1.add (Type); System.out.println (" ****  Serialization begins:  "); List<byte[]> result = serializeprotostufftypelist (List1); SYSTEM.OUT.PRINTLN ("Size of the serialized collection:"  + result.size ()); System.out.println (" ***********  deserialization start: "); List<type> l = deserializeprotostufftotypelist (result); System.out.println ("  The collection size after deserialization:"  + l.size ()  +  " , name1:"  +  L.get (0). Gettypename ());/***********  test  3 *****************/type type1 = new  type (); Type1.setcityid (2); Type1.setprice (New bigdecimal); Type1.settypename ("too"); SYSTEM.OUT.PRINTLN (" ------  Serialization start:"); byte[] type1ser = serializationutil.object2bytes _obj (type1); System.out.println (" -------  size after serialization:"  + type1ser.length); SYSTEM.OUT.PRINTLN (" ------  deserialization start:"); type type1result =  (Type) serializationutil.bytes2object (Type1ser); System.out.println (" ======  results after deserialization: Cityid:"  + type1result.getcityid ()  +  " ,typename:"  + type1result.gettypename ()  +   " , price:"  + type1result.getprice ());/********************  test 4 : Serialization Collection  **********************/type t2 = new type (); T2.setid (2); t2.setCityId (2); T2.setPrice ( New bigdecimal); T2.settypename ("ZHANG"); Arraylist<type> list2 = new arraylist<type> (); List2.add (T2); List2.add (t1); System.out.println (" ++++++++++++++    serialization start: ");byte[] result2 =   serializationutil.object2bytes (LIST2); System.out.println ("  Serialized size: "  + result2.length); System.out.println (" ++++++++++++++    serialization End: "); list<type> listresult =  (list<type>) serializationutil.bytes2object (RESULT2);   (Type t: listresult)  {system.out.println (T.gettypename ());}} /** *  the list collection of serialized type  * @param tlist *  @return  */public static List<byte[]>  Serializeprotostufftypelist (list<type> tlist)  {if  (tlist == null | |  tlist.size ()  <= 0)  {return null;} List<byte[]> bytes = new arraylist<byte[]> (); Schema<type> schema = runtimeschema.getschema (Type.class); Linkedbuffer buffer = linkedbuffer.allocate (1024x768); Byte[] protostuff = null;for ( type t: tlist)  {try {protostuff = protostuffioutil.tobytearray (T, schema,  buffer); Bytes.add (Protostuff);}  catch  (exception e)  {e.printstacktrace ();}  finally {buffer.clear ();}} Return bytes;} /** *  List collection for deserialization type  *  @param  bytesList *  @return  */public  Static list<type> deserializeprotostufftotypelist (list<byte[]> byteslist)  {if  (byteslist == null | |  byteslist.size ()  <= 0)  {return null;} Schema<type> schema = runtimeschema.getschema (Type.class); List<type> list = new arraylist<type> ();for  (byte[] bs :  byteslist)  {type type = new type (); Protostuffioutil.mergefrom (Bs, type, schema); List.add (type);} Return list;}}
package com.book.core.serializable;import java.io.serializable;public class  serializationutil {    public static protostuffserializer  Protostuffserializer;static {protostuffserializer = new protostuffserializer ();} Public static byte[] object2bytes (serializable obj)  throws exception {if   (Obj == null)  {return null;} Return protostuffserializer.serialize (obj);/*bytearrayoutputstream bo = new  Bytearrayoutputstream (); Objectoutputstream oo = new objectoutputstream (bo); Oo.writeObject ( obj); Bo.close (); Oo.close (); Return bo.tobytearray ();*/}/** *  Serialization "serialized object does not need to implement serializable"  *   @param  obj *  @return  *  @throws  Exception */public static  Byte[] object2bytes_obj (object obj)  throws Exception {if  (obj == null)  {Return null;} Return protostuffserializer.serialize (obj);} Public static byte[][] objects2bytes (serializable[] obj)  throws exception { if  (Obj == null)  {return null;} Byte[][] many = new byte[obj.length][];for (int i=0;i<obj.length;i++) {many[i]  = object2bytes (Obj[i]);} Return many;} Public static object bytes2object (byte[] objbytes)  throws exception {if   (objbytes == null | |  objbytes.length == 0)  {return null;} Object obj = protostuffserializer.deserialize (objbytes); Return obj;/*bytearrayinputstream  bi = new bytearrayinputstream (objbytes);objectinputstream oi = new  ObjectInputStream (BI); Obj = oi.readobject (); Bi.close (); Oi.close (); return obj;*/}}
package com.book.core.serializable;import com.dyuproject.protostuff.linkedbuffer;import  com.dyuproject.protostuff.protostuffioutil;import com.dyuproject.protostuff.schema;import  Com.dyuproject.protostuff.runtime.runtimeschema;import java.util.concurrent.concurrenthashmap;public  class protostuffserializer {    private static concurrenthashmap <class<?>, schema<?>> cachedschema = new concurrenthashmap<class <?>, Schema<?>> (    public <t> byte[] serialize); (Final t source)  {        vo<t> vo =  new VO<T> (source);         final linkedbuffer  buffer = linkedbuffer.allocate (linkedbuffer.default_buffer_size);         try {            final schema<vo> schema =  getschema (Vo.class);            return  Serializeinternal (vo, schema, buffer);         } catch   (final exception e)  {             throw new illegalstateexception (E.getmessage (),  e);         } finally {             Buffer.clear ();        }    }     public <t> t deserialize (final byte[] bytes)  {         try {             schema<vo> schema = getschema (vo.class);             vo  vo = deserializeinternal (Bytes, schema.newmessage (),  schema);             if  (vo != null &&  Vo.getvalue ()  != null)  {                 return  (T)  vo.getvalue ();             }        } catch  (final  Exception e)  {            throw new  illegalstateexception (E.getmessage (),  e);        }         return null;    }     Private <t> byte[]&nbSp;serializeinternal (final t source, final schema<t> schema, final  Linkedbuffer buffer)  {        return  Protostuffioutil.tobytearray (Source, schema, buffer);    }     private <t> t deserializeinternal (final byte[] bytes, final t  result, final schema<t> schema)  {         protostuffioutil.mergefrom (Bytes, result, schema);         return result;    }    private static <T>  schema<t> getschema (Class<t> clazz)  {          @SuppressWarnings ("unchecked")         Schema<T>  schema =  (schema<t>)  cachEdschema.get (Clazz);        if  (schema == null)  {             schema =  Runtimeschema.createfrom (Clazz);             Cachedschema.put (Clazz, schema);        }         return schema;    }}
package com.book.core.serializable;import java.io.serializable;/** * created by  Yijunzhang on 14-4-2. */public class vo<t> implements serializable  {    private t value;    public vo (T value)  {        this.value = value;    }     public vo ()  {    }    public t  getvalue ()  {        return value;     }     @Override     public string tostring ()  {         return  "vo{"  +                  "Value="  + value +                  '} ';     }    @ Override    public boolean equals (Object o)  {         if  (This == o)  return true;         if  (!) ( O&NBSP;INSTANCEOF&NBSP;VO))  return false;        vo vo  =  (VO)  o;        if  (value != null  ? !value.equals (vo.value)  : vo.value != null)  return false;         return true;    }    @ Override    public int hashcode ()  {         return value != null ? value.hashcode ()  : 0;   & nbsp;}} 
package com.book.core.model;import java.math.bigdecimal;public class type {     private Integer id;    private String typeName;     private BigDecimal price;    private Integer  Cityid;    public integer getid ()  {         return id;    }    public void setid ( Integer id)  {        this.id = id;     }    public string gettypename ()  {         return typename;    }    public void  settypename (String typename)  {        this.typename  = typename == null&nbSP;?  null : typename.trim ();     }    public bigdecimal  getprice ()  {        return price;     }    public void setprice (Bigdecimal price)  {         this.price = price;    }     Public integer getcityid ()  {        return cityId;     }    public void setcityid (Integer cityId)  {         this.cityid = cityid;    }}
<dependency>  <groupid>com.dyuproject.protostuff </groupid>  <artifactid>protostuff-core</artifactid>  <version>${ Protostuff.version}</version></dependency><dependency>  <groupid> Com.dyuproject.protostuff</groupid>  <artifactid>protostuff-runtime</artifactid>   <version>${protostuff.version}</version></dependency><dependency>   <groupId>com.dyuproject.protostuff</groupId>  <artifactId>protostuff-api< /artifactid>  <version>${protostuff.version}</version></dependency>< Dependency>  <groupid>com.dyuproject.protostuff</groupid>  <artifactid >protostuff-collectionschema</artifactid>  <version>${protostuff.version}</version ></dependency> 
<protostuff.version>1.0.8</protostuff.version>

Several ways to serialize

http://my-corner.iteye.com/blog/1776512



Java Serialization Simple understanding

http://hanchaohan.blog.51cto.com/2996417/922470



Jprotobuf's Simple understanding

Https://github.com/jhunters/jprotobuf



Java serialization/deserialization XStream, Protobuf, protostuff comparison and usage examples

Http://www.cnblogs.com/xiaoMzjm/p/4555209.html



This article is from the "My Java World" blog, so be sure to keep this source http://hanchaohan.blog.51cto.com/2996417/1962798

The Protobuf of Java serialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.