天天看點

Google Protocol Buffer(1)—Overview

引言

google protocol buffer :一個語言無關,平台無關,可擴充的結構化資料序列化的方法,可用于通信協定,資料存儲等;

(protocol buffers – a language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage, and more.)

1.什麼是google protocol buffer 

  • protocol buffer 是一個靈活、高效、自動的序列化結構化資料的方法,功能上類似于XML,但更小、更快、更簡單;
  • 開發者定于資料結構,使用protobuf的代碼生成器生成代碼實作不同資料流的讀寫;
  • 向後相容性好:在不破壞已部署的、依靠“老”資料結構的程式就可以對資料結構更新;這樣程式就不會因為消息結構的改變而造成的大規模的代碼重構或者遷移的問題。因為新添加的filed 并不會引起已經釋出的程式的任何改變;

2.使用protobuf的開發流程

  • 定義消息結構:編輯 .proto檔案;以定義person.proto為例:
    message Person {
      required string name = 1;
      required int32 id = 2;
      optional string email = 3;
    
      enum PhoneType {
        MOBILE = 0;
        HOME = 1;
        WORK = 2;
      }
    
      message PhoneNumber {
        required string number = 1;
        optional PhoneType type = 2 [default = HOME];
      }
    
      repeated PhoneNumber phone = 4;
    }      
  • 使用protobuf提供的代碼生成器生成CLASS Person類的頭檔案及其實作:message.person.h, message.person.cc;
  • 使用提供的accessors即可實作消息體各個字段的讀寫:query();set_query();
  • 下面是一個典型的結構化資料person先寫入一個檔案中再從檔案中讀出的demo:
Person person;
person.set_name("John Doe");
person.set_id(1234);
person.set_email("[email protected]");
fstream output("myfile", ios::out | ios::binary);
person.SerializeToOstream(&output);      
fstream input("myfile", ios::in | ios::binary);
Person person;
person.ParseFromIstream(&input);
cout << "Name: " << person.name() << endl;
cout << "E-mail: " << person.email() << endl;      
  • 可以在message中增加新的filed,已有的message解析子產品會相容;

3.protocol buffer的優點

  • 小3-10倍;
  • 快20-100倍;
  • 歧義性更少;
  • 簡單;

4.protobuf可以解決那些問題?

  • 自動将結構化資料序列化和發序列化;
  • RPC系統;

繼續閱讀