Google Protocol Buffer(1)—Overview

引言

google protocol buffer :一个语言无关,平台无关,可扩展的结构化数据序列化的方法,可用于通信协议,数据存储等;

(protocol buffers – a language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage, and more.)

1.什么是google protocol buffer 

  • protocol buffer 是一个灵活、高效、自动的序列化结构化数据的方法,功能上类似于XML,但更小、更快、更简单;
  • 开发者定于数据结构,使用protobuf的代码生成器生成代码实现不同数据流的读写;
  • 向后兼容性好:在不破坏已部署的、依靠“老”数据结构的程序就可以对数据结构升级;这样程序就不会因为消息结构的改变而造成的大规模的代码重构或者迁移的问题。因为新添加的filed 并不会引起已经发布的程序的任何改变;

2.使用protobuf的开发流程

  • 定义消息结构:编辑 .proto文件;以定义person.proto为例:
    message Person {
      required string name = 1;
      required int32 id = 2;
      optional string email = 3;
    
      enum PhoneType {
        MOBILE = 0;
        HOME = 1;
        WORK = 2;
      }
    
      message PhoneNumber {
        required string number = 1;
        optional PhoneType type = 2 [default = HOME];
      }
    
      repeated PhoneNumber phone = 4;
    }
  • 使用protobuf提供的代码生成器生成CLASS Person类的头文件及其实现:message.person.h, message.person.cc;
  • 使用提供的accessors即可实现消息体各个字段的读写:query();set_query();
  • 下面是一个典型的结构化数据person先写入一个文件中再从文件中读出的demo:
Person person;
person.set_name("John Doe");
person.set_id(1234);
person.set_email("jdoe@example.com");
fstream output("myfile", ios::out | ios::binary);
person.SerializeToOstream(&output);
fstream input("myfile", ios::in | ios::binary);
Person person;
person.ParseFromIstream(&input);
cout << "Name: " << person.name() << endl;
cout << "E-mail: " << person.email() << endl;

  • 可以在message中增加新的filed,已有的message解析模块会兼容;
3.protocol buffer的优点
  • 小3-10倍;
  • 快20-100倍;
  • 歧义性更少;
  • 简单;
4.protobuf可以解决那些问题?

  • 自动将结构化数据序列化和发序列化;
  • RPC系统;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值