項目中使用protobuf


在互種系統中數據通信或數據交換可以使用protobuf,他比json、xml的數據量要小一些。

另外因為消息要單獨寫一個.proto文件,來生成各平台的代碼,所以對跨平台通信來說也比較友好。

一。使用方法

  1.編寫.proto文件,定義格式

  2.用所需源文件的編譯器編譯.proto文件,生成所需的源文件,官方的編譯器只支持  ,c++、java、python,c#可以用:https://github.com/mgravell/protobuf-net 或者用我編譯好的:http://pan.baidu.com/s/1i4S43PV

  3.將所需的源文件加入到項目中。另外還需要支持的庫文件

  另外c#的各位,如果是運行在xamarin或其它對反射有限制的地方最好還要看下這個:http://blog.marcgravell.com/2012/07/introducing-protobuf-net-precompiler.html

二。protobuf消息定義(來自:http://blog.csdn.net/dahuaishu2010_/article/details/41867047)

  protobuf的每個結構都是一個message,對應C#里的一個類。

  1.消息由至少一個字段組合而成,類似於C語言中的結構。每個字段都有一定的格式。

    字段格式:限定修飾符① | 數據類型② | 字段名稱③ | = | 字段編碼值④ | [字段默認值⑤]

    ①.限定修飾符包含 required\optional\repeated

       Required: 表示是一個必須字段,必須相對於發送方,在發送消息之前必須設置該字段的值,對於接收方,必須能夠識別該字段的意思。發送之前沒有設置required字段或者無法識別required字段都會引發編解碼異常,導致消息被丟棄。

       Optional:表示是一個可選字段,可選對於發送方,在發送消息時,可以有選擇性的設置或者不設置該字段的值。對於接收方,如果能夠識別可選字段就進行相應的處理,如果無法識別,則忽略該字段,消息中的其它字段正常處理。---因為optional字段的特性,很多接口在升級版本中都把后來添加的字段都統一的設置為optional字段,這樣老的版本無需升級程序也可以正常的與新的軟件進行通信,只不過新的字段無法識別而已,因為並不是每個節點都需要新的功能,因此可以做到按需升級和平滑過渡。

       Repeated:表示該字段可以包含0~N個元素。其特性和optional一樣,但是每一次可以包含多個值。可以看作是在傳遞一個數組的值。 

    ②.數據類型

       Protobuf定義了一套基本數據類型。幾乎都可以映射到C++\Java等語言的基礎數據類型.

      

protobuf 數據類型

描述

打包

C++語言映射

bool

布爾類型

1字節

bool

double

64位浮點數

N

double

float

32為浮點數

N

float

int32

32位整數、

N

int

uin32

無符號32位整數

N

unsigned int

int64

64位整數

N

__int64

uint64

64為無符號整

N

unsigned __int64

sint32

32位整數,處理負數效率更高

N

int32

sing64

64位整數 處理負數效率更高

N

__int64

fixed32

32位無符號整數

4

unsigned int32

fixed64

64位無符號整數

8

unsigned __int64

sfixed32

32位整數、能以更高的效率處理負數

4

unsigned int32

sfixed64

64為整數

8

unsigned __int64

string

只能處理 ASCII字符

N

std::string

bytes

用於處理多字節的語言字符、如中文

N

std::string

enum

可以包含一個用戶自定義的枚舉類型uint32

N(uint32)

enum

message

可以包含一個用戶自定義的消息類型

N

object of class

      N 表示打包的字節並不是固定。而是根據數據的大小或者長度。

      例如int32,如果數值比較小,在0~127時,使用一個字節打包。

      關於枚舉的打包方式和uint32相同。

      關於message,類似於C語言中的結構包含另外一個結構作為數據成員一樣。

      關於 fixed32 和int32的區別。fixed32的打包效率比int32的效率高,但是使用的空間一般比int32多。因此一個屬於時間效率高,一個屬於空間效率高。根據項目的實際情況,一般選擇fixed32,如果遇到對傳輸數據量要求比較苛刻的環境,可以選擇int32.

    ③.字段名稱 

      字段名稱的命名與C、C++、Java等語言的變量命名方式幾乎是相同的。

      protobuf建議字段的命名采用以下划線分割的駝峰式。例如 first_name 而不是firstName.

    ④.字段編碼值

      有了該值,通信雙方才能互相識別對方的字段。當然相同的編碼值,其限定修飾符和數據類型必須相同。

      編碼值的取值范圍為 1~2^32(4294967296)。

      其中 1~15的編碼時間和空間效率都是最高的,編碼值越大,其編碼的時間和空間效率就越低(相對於1-15),當然一般情況下相鄰的2個值編碼效率的是相同的,除非2個值恰好實在4字節,12字節,20字節等的臨界區。比如15和16.

      1900~2000編碼值為Google protobuf 系統內部保留值,建議不要在自己的項目中使用。

      protobuf 還建議把經常要傳遞的值把其字段編碼設置為1-15之間的值。

      消息中的字段的編碼值無需連續,只要是合法的,並且不能在同一個消息中有字段包含相同的編碼值。

      建議:項目投入運營以后涉及到版本升級時的新增消息字段全部使用optional或者repeated,盡量不實用required。如果使用了required,需要全網統一升級,如果使用optional或者repeated可以平滑升級。

 

    ⑤.默認值。當在傳遞數據時,對於required數據類型,如果用戶沒有設置值,則使用默認值傳遞到對端。當接受數據是,對於optional字段,如果沒有接收到optional字段,則設置為默認值。

      關於import

        protobuf 接口文件可以像C語言的h文件一個,分離為多個,在需要的時候通過 import導入需要對文件。其行為和C語言的#include或者java的import的行為大致相同。

      關於package

        避免名稱沖突,可以給每個文件指定一個package名稱,對於java解析為java中的包。對於C++則解析為名稱空間。

      關於message

        支持嵌套消息,消息可以包含另一個消息作為其字段。也可以在消息內定義一個新的消息。

      關於enum

        枚舉的定義和C++相同,但是有一些限制。

        枚舉值必須大於等於0的整數。

        使用分號(;)分隔枚舉變量而不是C++語言中的逗號(,)

        

enum VoipProtocol 
{
    H323 = 1;
    SIP  = 2;
    MGCP = 3;
    H248 = 4;
}

 

三。演示

  1.proto示例:ehr_person  

package ZTImage.Inone.Domain;

message ehr_person
{
    required string personid=1;
    required int32 age=2;
    required string name=3;
    optional string email=4;

    enum PhoneType
    {
        Mobile=0;
        Home=1;
        Work=2;
    }

    message PhoneNumber
    {
        required string number=1;
        optional PhoneType type=2 [default=Home];
    }

    repeated PhoneNumber phones=5;
}


message AddressBook
{
    repeated ehr_person persons=1;
}

  2.C#版本

    執行:protogen.exe -i:ehr_person.proto -o:ehr_person.cs

    ehr_person.cs文件內容為:

    

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

// Generated from: ehr_person.proto
namespace ZTImage.Inone.Domain
{
  [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ehr_person")]
  public partial class ehr_person : global::ProtoBuf.IExtensible
  {
    public ehr_person() {}
    
    private string _personid;
    [global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"personid", DataFormat = global::ProtoBuf.DataFormat.Default)]
    public string personid
    {
      get { return _personid; }
      set { _personid = value; }
    }
    private int _age;
    [global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"age", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
    public int age
    {
      get { return _age; }
      set { _age = value; }
    }
    private string _name;
    [global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"name", DataFormat = global::ProtoBuf.DataFormat.Default)]
    public string name
    {
      get { return _name; }
      set { _name = value; }
    }
    private string _email = "";
    [global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"email", DataFormat = global::ProtoBuf.DataFormat.Default)]
    [global::System.ComponentModel.DefaultValue("")]
    public string email
    {
      get { return _email; }
      set { _email = value; }
    }
    private readonly global::System.Collections.Generic.List<ZTImage.Inone.Domain.ehr_person.PhoneNumber> _phones = new global::System.Collections.Generic.List<ZTImage.Inone.Domain.ehr_person.PhoneNumber>();
    [global::ProtoBuf.ProtoMember(5, Name=@"phones", DataFormat = global::ProtoBuf.DataFormat.Default)]
    public global::System.Collections.Generic.List<ZTImage.Inone.Domain.ehr_person.PhoneNumber> phones
    {
      get { return _phones; }
    }
  
  [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PhoneNumber")]
  public partial class PhoneNumber : global::ProtoBuf.IExtensible
  {
    public PhoneNumber() {}
    
    private string _number;
    [global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"number", DataFormat = global::ProtoBuf.DataFormat.Default)]
    public string number
    {
      get { return _number; }
      set { _number = value; }
    }
    private ZTImage.Inone.Domain.ehr_person.PhoneType _type = ZTImage.Inone.Domain.ehr_person.PhoneType.Home;
    [global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"type", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
    [global::System.ComponentModel.DefaultValue(ZTImage.Inone.Domain.ehr_person.PhoneType.Home)]
    public ZTImage.Inone.Domain.ehr_person.PhoneType type
    {
      get { return _type; }
      set { _type = value; }
    }
    private global::ProtoBuf.IExtension extensionObject;
    global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
      { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
  }
  
    [global::ProtoBuf.ProtoContract(Name=@"PhoneType")]
    public enum PhoneType
    {
            
      [global::ProtoBuf.ProtoEnum(Name=@"Mobile", Value=0)]
      Mobile = 0,
            
      [global::ProtoBuf.ProtoEnum(Name=@"Home", Value=1)]
      Home = 1,
            
      [global::ProtoBuf.ProtoEnum(Name=@"Work", Value=2)]
      Work = 2
    }
  
    private global::ProtoBuf.IExtension extensionObject;
    global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
      { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
  }
  
  [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"AddressBook")]
  public partial class AddressBook : global::ProtoBuf.IExtensible
  {
    public AddressBook() {}
    
    private readonly global::System.Collections.Generic.List<ZTImage.Inone.Domain.ehr_person> _persons = new global::System.Collections.Generic.List<ZTImage.Inone.Domain.ehr_person>();
    [global::ProtoBuf.ProtoMember(1, Name=@"persons", DataFormat = global::ProtoBuf.DataFormat.Default)]
    public global::System.Collections.Generic.List<ZTImage.Inone.Domain.ehr_person> persons
    {
      get { return _persons; }
    }
  
    private global::ProtoBuf.IExtension extensionObject;
    global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
      { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
  }
  
}

 使用:

  引用protobuf-net:nuget可以得到

把ehr_person.cs放入項目中

  

 ZTImage.Inone.Domain.AddressBook book = new Inone.Domain.AddressBook();
            for (int i = 0; i < 100; i++)
            {
                ZTImage.Inone.Domain.ehr_person person = new Inone.Domain.ehr_person();
                person.age = i;
                person.email = i.ToString() + "@hotmail.com";
                person.phones.Add( new Inone.Domain.ehr_person.PhoneNumber() { number = i.ToString(), type = Inone.Domain.ehr_person.PhoneType.Work } );
                person.personid = i.ToString();
                person.name = i.ToString() + "name";
                
                book.persons.Add(person);
            }

            using (var stream = File.Create("d:\\persons.bin"))
            {
                ProtoBuf.Serializer.Serialize<ZTImage.Inone.Domain.AddressBook>(stream, book);
            }

生成的文件為3.8k

讀取:

  

 using (var stream = File.OpenRead("d:\\persons.bin"))
            {
                var books=ProtoBuf.Serializer.Deserialize<ZTImage.Inone.Domain.AddressBook>(stream);

                Console.WriteLine("通訊錄個數:"+books.persons.Count);
                
            }

            Console.ReadKey();

運行結果:

 

 

  

 


免責聲明!

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



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