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

运行结果:

3.Java版

4.C++版

  

  

时间: 2024-08-08 04:11:51

项目中使用protobuf的相关文章

在erlang项目中使用protobuf

在erlang项目中使用protobuf http://blog.csdn.net/mycwq/article/details/21864191 protobuf是google的一个序列化框架,类似XML,JSON,其特点是基于二进制,比XML表示同样一段内容要短小得多,还可以定义一些可选字段,广泛用于服务端与客户端通信.文章将着重介绍在erlang中如何使用protobuf. 首先google没有提供对erlang语言的直接支持,所以这里使用到的第三方的protobuf库(erlang_pro

项目中使用protobuf 3.0

protocol buffer从3.0 原生的compiler支持c++,Java,Python,Go,Ruby,JavaNano,JavaScript,Objective-C,C#,PHP这篇文章作为上一篇文章的补充,简单记录下一些变化. protobuf的开源地址为:https://github.com/google/protobuf protocol compiler下载地址为:https://github.com/google/protobuf/releases 官方定义message类

Erlang 在erlang项目中使用protobuf

protobuf是google的一个序列化框架,类似XML,JSON,其特点是基于二进制,比XML表示同样一段内容要短小得多,还可以定义一些可选字段,广泛用于服务端与客户端通信.文章将着重介绍在erlang中如何使用protobuf. 首先google没有提供对erlang语言的直接支持,所以这里使用到的第三方的protobuf库( erlang_protobuffs ) 定义一个protobuf结构,保存为test.proto,如下: message Person { required int

在java项目中使用protobuf

1 通用方式 第一步,定义数据结构 第二步,使用protoc.exe生成java代码 第三步,序列化 第四步,反序列化 2 grpc方式 grpc官方推荐的方式,通过maven插件来生成java代码. 参考 https://www.cnblogs.com/liugh/p/7505533.html 原文地址:https://www.cnblogs.com/hustdc/p/9131346.html

【新手总结】在.Net项目中使用Redis作为缓存服务

最近由于项目需要,在系统缓存服务部分上了redis,终于有机会在实际开发中玩一下,之前都是自己随便看看写写,很零碎也没沉淀下来什么,这次算是一个系统学习和实践过程的总结. 和Redis有关的基础知识 Redis是一个开源的分布式NoSql数据库,可以用来做缓存服务.消息队列.数据存储等等,数据类型之丰富,效率之高,简直逆天!没有了解过的可以移步去问度娘~客户端之丰富,足可见它的社区有多强大: 其中C#的客户端就有这么多: 没错,我们的项目里也选择了最热门的StackExchange.Redis作

cocos2d-x lua 中使用protobuf并对http进行处理

本文介绍 cocos2d-x lua 中使用http 和 基于cocos2d-x 对lua http的封装(部分ok) 本博客链接 http://blog.csdn.net/vpingchangxin/article/details/24458051 protobuf  Google的一个非常好用的数据传输的封装 说实话Google的东西确实比較好用 所以我们前后端数据交换就用他了 只是Google没有对lua进行支持 还好社区有开源的大侠们贡献 找了全部关于lua protobuf 我仅仅找到

用Netty和Raphael来写塔防online游戏(二) - JS中使用protobuf协议

一. 简单介绍一下protobuf: Protocol Buffers are a language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage, and more, originally designed at Google . 如今,已经有人用JS实现了protobuf协议,就是ProtoBu

在as3中使用protobuf

在最近参与开发的adobe air项目中,前后端的通信协议从XML.JSON再到protobuf,最后选择protobuf原因,主要是前后端维护protobuf协议就行了,同时还可以利用IDE做一些编译检查.目前我能找到的protobuf as3开源库,都存在一些问题:不支持嵌套类,生成代码无法编译等等.于是花了一点时间,参考google protobuf相关说明,编写protobuf-as3以及protoc-as3,用于支持运行时及代码生成,https://github.com/zhongfq

用java写一个远程视频监控系统,实时监控(类似直播)我想用RPT协议,不知道怎么把RPT协议集成到项目中

我最近在用java写一个远程视频监控系统,实时监控(类似直播)我想用RPT协议,不知道怎么把RPT协议集成到项目中,第一次写项目,写过这类项目的多多提意见,哪方面的意见都行,有代码或者demo的求赏给我,谢谢