Google Protocol Buffers 入門


Google Protocol Buffers 是一種輕便高效的結構化數據存儲格式,可以用於結構化數據串行化,或者說序列化。它很適合做數據存儲或 RPC 數據交換格式。可用於通訊協議、數據存儲等領域的語言無關、平台無關、可擴展的序列化結構數據格式。目前支持主流的語言(java\c++\python\c#\go....)。

具官方說法使用PB 進行序列化和反序列化性能是xml序列化和反序列化的20~100倍,在各種序列化和反序列化方式中,處於領先地位。

PB的序列化結果是字節與字節的連接,省略了字段名稱,在存儲上也比其他方式要小,更節省空間。不過這樣帶來了可讀性變差和調試困難。

 

官方源碼:https://github.com/google/protobuf

各版本的編譯結果下載地址:https://github.com/google/protobuf/releases

 

官方介紹:https://developers.google.com/protocol-buffers/

 

 

1、下載protoc

在https://github.com/google/protobuf/releases中,可以看到多個系統的protoc文件:

protoc-3.3.0-linux-x86_32.zip                           

protoc-3.3.0-linux-x86_64.zip        

protoc-3.3.0-osx-x86_32.zip           

protoc-3.3.0-osx-x86_64.zip                          

protoc-3.3.0-win32.zip

下載后,解壓就可以。

 

 

 

 

2、在解壓目錄創建一個*.proto 文件。

如:test.proto

syntax = "proto3"; 

message test{  

  double Id=1;   

string Name=2;

}

syntax = "proto3"; 為指定一個版本,此含義為使用proto3

message為關鍵字,test為類名

double/string為類字段類型,Id/Name為字段屬性,1/2為存儲序號,定義后不可變

詳細定義和使用方法參考:https://developers.google.com/protocol-buffers/docs/proto3#simple

 

3、生成各種語言的類文件

protoc --cpp_out="./"  --java_out="./"   --csharp_out="./"  ./test.proto

“./”為當前protoc所在目錄,protoc為可執行文件

 

4、序列化與反序列化(以下C#示例)

 Google.Protobuf.IMessage test= new test() {  Id= 3333555555234234.333, Name= "dfsdfsdfsdfsdfsdfsdfs"};  //創建test對象

 byte[] buf = null;
 using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
 {
     //序列化
     using (Google.Protobuf.CodedOutputStream output = new Google.Protobuf.CodedOutputStream(ms))
     {
        test.WriteTo(output);
     }

                    
     buf = ms.ToArray();
 }

 test newTest = new test();
 using (Google.Protobuf.CodedInputStream input = new Google.Protobuf.CodedInputStream(buf))
 {
     //反序列化
     newTest.MergeFrom(input);
 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM