项目中使用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();

运行结果:

相关文章
相关标签/搜索