項目中使用protobuf

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

另外由於消息要單獨寫一個.proto文件,來生成各平臺的代碼,因此對跨平臺通訊來講也比較友好。java

一。使用方法python

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

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

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

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

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

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

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

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

    ①.限定修飾符包含 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();

運行結果:

相關文章
相關標籤/搜索