大家好,欢迎来到IT知识分享网。
packagecom.common.utils;importio.protostuff.LinkedBuffer;importio.protostuff.ProtostuffIOUtil;importio.protostuff.Schema;importio.protostuff.runtime.RuntimeSchema;/***
* @desc protobuf序列化反序列化工具
*@authorwulm*/
public classProtostuffUtil{/*** @desc protostuff 目前不支持直接序列化List等对象,需要使用普通的POJO包装一下
*@authorwulm*/
private static classSerializeData {privateObject target;publicObject getTarget() {returntarget;
}public voidsetTarget(Object target) {this.target =target;
}
}private static final ThreadLocal BUFFER_THREAD_LOCAL =ThreadLocal
.withInitial(()-> LinkedBuffer.allocate(512));/*** @desc 序列化
* @auth wulm*/@SuppressWarnings(“unchecked”)public static byte[] serialize(Object obj) {
SerializeData data= newSerializeData();
data.setTarget(obj);//this is lazily created and cached by RuntimeSchema//so its safe to call RuntimeSchema.getSchema(Foo.class) over and over//The getSchema method is also thread-safe
Schema schema = RuntimeSchema.getSchema((Class) data.getClass());//Re-use (manage) this buffer to avoid allocating on every serialization//LinkedBuffer buffer = LinkedBuffer.allocate(512);
LinkedBuffer buffer =BUFFER_THREAD_LOCAL.get();//ser
try{returnProtostuffIOUtil.toByteArray(data, schema, buffer);
}catch(Exception e) {throw newIllegalStateException(e.getMessage(), e);
}finally{
buffer.clear();
}
}/***
* @desc 反序列化
* @auth wulm*/@SuppressWarnings(“unchecked”)public static T deserialize(byte[] data, Classcls) {
Schema schema = RuntimeSchema.getSchema(SerializeData.class);//deser
SerializeData message =schema.newMessage();
ProtostuffIOUtil.mergeFrom(data, message, schema);return(T) message.getTarget();
}//public static class Aaa {//
//public static void main(String[] args) {//
//Aaa aaa = new Aaa();//aaa.setA(“你好呀”);//aaa.setB(“我是佩琪”);//aaa.setC(“你好”);//aaa.setD(“我是猪爸爸”);//
//List list = new ArrayList<>();//list.add(aaa);//
//byte[] serialize = ProtostuffUtil.serialize(list);//
//List bb = ProtostuffUtil.deserialize(serialize,//List.class);//
//System.out.println(JacksonUtils.writeValueAsString(bb));//
//}//
//private String a;//private String b;//private String c;//private String d;//
//public String getA() {//return a;//}//
//public void setA(String a) {//this.a = a;//}//
//public String getB() {//return b;//}//
//public void setB(String b) {//this.b = b;//}//
//public String getC() {//return c;//}//
//public void setC(String c) {//this.c = c;//}//
//public String getD() {//return d;//}//
//public void setD(String d) {//this.d = d;//}//
//}
}
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/21898.html