zoukankan      html  css  js  c++  java
  • 项目中使用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语言中的结构。每个字段都有一定的格式。

        字段格式:限定修饰符① | 数据类型② | 字段名称③ | = | 字段编码值④ | [字段默认值⑤]

        ①.限定修饰符包含 requiredoptional epeated

           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();

    运行结果:

      

  • 相关阅读:
    servlet中如何实现通过Spring实现对象的注入
    异步Socket
    JAVA NIO实现
    【Java并发】
    JAVA实现阻塞队列
    lock与synchronized比较
    线程执行顺序
    ConcurrentHashMap 1.8
    LeetCode 416 分割等和子集
    linux常用指令
  • 原文地址:https://www.cnblogs.com/asminfo/p/6601378.html
Copyright © 2011-2022 走看看