Google Protobuf简明教程

Protobuf是什么

Protobuf实际是一套相似Json或者XML的数据传输格式和规范,用于不一样应用或进程之间进行通讯时使用。通讯时所传递的信息是经过Protobuf定义的message数据结构进行打包,而后编译成二进制的码流再进行传输或者存储。css

Protobuf的优势

相比较而言,Protobuf有以下优势:python

  • 足够简单
  • 序列化后体积很小:消息大小只须要XML的1/10 ~ 1/3
  • 解析速度快:解析速度比XML快20 ~ 100倍
  • 多语言支持
  • 更好的兼容性,Protobuf设计的一个原则就是要可以很好的支持向下或向上兼容

如何安装使用Protobuf

安装

使用Python的话简便的安装方法以下git

pip install protobuf    # 安装protobuf库
sudo apt-get install protobuf-compiler # 安装protobuf编译器 

若是本身编译安装的话能够参考git上安装指导,虽然写得不清楚:)github

使用

使用Protobuf有以下几个步骤:数据结构

  1. 定义消息
  2. 初始化消息以及存储传输消息
  3. 读取消息并解析

下面以一个实际的例子来讲明如何使用Protobuf,先展现出项目的实际目录结构:ide

.
├── my
│   ├── helloworld_pb2.py
│   ├── helloworld_pb2.pyc
│   └── __init__.py
├── mybuffer.io
├── my.helloworld.proto
├── reader.py
└── writer.py

定义消息

Protobuf的消息结构是经过一种叫作Protocol Buffer Language的语言进行定义和描述的,实际上Protocol Buffer Language分为两个版本,版本2和版本3,默认不声明的状况下使用的是版本2,下面以版本2为来举个栗子, 假设咱们定义了文件名为my.helloworld.proto的文件,以下:ui

package my; message helloworld { required int32 id = 1; required string str = 2; optional int32 wow = 3; } 

而后咱们须要使用protoc进行编译google

protoc -I=./ --python_out=./ ./my.helloworld.proto
  • -I: 是设定源路径
  • --python_out: 用于设定编译后的输出结果,若是使用其它语言请使用对应语言的option
  • 最后一个参数是你要编译的proto文件

如今已经定义好了消息的数据结构,接下来看下如何使用spa

消息初始化和存储传输

咱们来经过writer.py来初始化消息并存储为文件,代码以下:设计

from my.helloworld_pb2 import helloworld def main(): hw = helloworld() hw.id = 123 hw.str = "eric" print hw with open("mybuffer.io", "wb") as f: f.write(hw.SerializeToString()) if __name__ == "__main__": main() 

执行writer.py以后就会将序列化的结果存储在文件mybuffer.io中,而后看下如何读取

消息读取与解析

咱们经过reader.py来读取和解析消息,代码以下:

from my.helloworld_pb2 import helloworld def main(): hw = helloworld() with open("mybuffer.io", "rb") as f: hw.ParseFromString(f.read()) print hw.id print hw.str if __name__ == "__main__": main() 

Reference:

做者:geekpy 连接:https://www.jianshu.com/p/b723053a86a6 来源:简书 著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。