importio.protostuff.LinkedBuffer;importio.protostuff.ProtostuffIOUtil;importio.protostuff.Schema;importio.protostuff.runtime.RuntimeSchema;importjava.io.Serializable;importjava.util.Map;importjava.util.concurrent.ConcurrentHashMap;/*** Protostuff serializer tool, for POJO serialization.
* Protostuff is much more efficient than json, even faster than Protobuf and Avro, but the serialized string is human-unreadable.
* Not support Array or Generic-type, please wrap these special objects via a POJO with empty constructors.
*
*@authorlhfcws
*@since2016-03-16*/
public class ProtostuffSerializer implementsSerializable {static Map schemaCache = new ConcurrentHashMap<>();/*** common protostuff serialize, object need a empty constructor
* Be careful to convert result byte[] to String, use new String(bytes, StandardCharsets.UTF_16LE).
*
*@paramobj
*@param
*@return
*/
public static byte[] serializeObject(T obj) {
Class klass = (Class) obj.getClass();
LinkedBuffer buffer= LinkedBuffer.allocate(4096);
try {if(schemaCache.containsKey(klass)) {returnProtostuffIOUtil.toByteArray(obj, schemaCache.get(klass), buffer);
}else{
schemaCache.put(klass, RuntimeSchema.getSchema(klass));returnProtostuffIOUtil.toByteArray(obj, schemaCache.get(klass), buffer);
}
} finally {
buffer.clear();
}
}/*** common protostuff unserialize
*
*@parambs
*@paramklass
*@param
*@return
*/
public static T deserialize(byte[] bs, Classklass) {if(schemaCache.containsKey(klass)) {
Schema schema =schemaCache.get(klass);
T msg=schema.newMessage();
ProtostuffIOUtil.mergeFrom(bs, msg, schema);returnmsg;
}else{
Schema schema =RuntimeSchema.getSchema(klass);
T msg=schema.newMessage();
schemaCache.put(klass, schema);
ProtostuffIOUtil.mergeFrom(bs, msg, schema);returnmsg;
}
}
}