pb实现

294 阅读1分钟

1 参考文献

Protocol Buffer序列化Java框架-Protostuff_Silence__lei的博客-CSDN博客

(17条消息) Protocol Buffer 序列化_believe_s的博客-CSDN博客

2 pb简介

Protobuf是Google开发的一种独立和轻量级的数据交换格式,以二进制结构进行存储,用于不同服务之间序列化数据。全称为Protocol Buffers,是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者序列化,可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。

3 pd的文件格式

4 pd使用框架 ProtoStuff

Google对于Protocol Buffer提供了多种语言的实现方法:Java,C++,go和python。但我们在使用时仍然需要去编写可读性不高的.proto文件,然后使用Google提供的实现方法编译成对应的语言,这就提高了我们使用Protocol Buffer的门槛。因此ProtoStuff就诞生了,通过ProtoStuff这个框架,我们能直接将对象通过Protocol Buffer这种序列化的方式转成对应的字节,极大地降低了我们使用Protocol Buffer的使用成本。

5 代码实现

框架 + 泛型 + 反射 大部分的序列化都是框架做的

//序列化的方法
public static <T> byte[] serialize(T obj) throws IOException {    
     Class<T> cls = (Class<T>) obj.getClass();    
     LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);   
     try {       
           Schema<T> schema = getSchema(cls);        
           byte[] bytes =  ProtobufIOUtil.toByteArray(obj, schema, buffer);        
           IOUtils.write(bytes);        
           return bytes;    
         } catch (Exception e) {       
           throw new IllegalStateException(e.getMessage(), e);    
        } finally {       
             buffer.clear();    
        }
  }



//反序列化的方法
public static <T> T deserialize(byte[] data, Class<T> cls) throws IOException{    
     try {        
            T message = cls.newInstance();        
            Schema<T> schema = getSchema(cls);        
            ProtobufIOUtil.mergeFrom(data, message, schema);        
            return message;    
         } catch (Exception e) {        
            throw new IllegalStateException(e.getMessage(), e);    
         }
     }



@Test
public void test(){    
     try {        
            pbDemo.getSample();        //序列化测试        
            byte[] bytes = pbDemo.serialize(pbDemo.getPersonDemo());        
            Class objectClass = pbDemo.getPersonDemo().getClass();        //反序列化测试
            Object object = pbDemo.deserialize(bytes, objectClass);        
            System.out.println(object.toString());    
          }catch (IOException e){        
             e.printStackTrace();    
          }
}