来源于我的个人博客, 原文用markdown编写,转到csdn格式有些问题。
简介
Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准,目前已经正在使用的有超过 48,162 种报文格式定义和超过 12,183 个 .proto 文件。他们用于 RPC 系统和持续数据存储系统。
Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。它很适合做数据存储或 RPC 数据交换格式。可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。目前提供了 C++、Java、Python 三种语言的 API。
入门
下载安装protobuf后编写hello.proto文件
|
|
.proto文件定义需要进行序列化和反序列化数据的格式。具体参考官方文档。其中的required,optional的官方说明如下
Specifying Field Rules
You specify that message fields are one of the following:
required:
a well-formed message must have exactly one of this field.
optional:
a well-formed message can have zero or one of this field (but not more than one).
repeated:
this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.
定义中的
|
|
1是id在message helloword中的数字标签,这个标签在一个message中是唯一的,一旦定义后在使用时就不能再改变。
each field in the message definition has a unique numbered tag. These tags are used to identify your fields in the message binary format, and should not be changed once your message type is in use.
编译 .proto 文件
写好 proto 文件之后就可以用 Protobuf 编译器将该文件编译成目标语言了。本例中我们将使用 C++。
假设proto 文件存放在 SRC_DIR 下面,生成的文件放在DST_DIR目录下,则可以使用如下命令:
|
|
编写writer.cpp
|
|
编译&运行
|
|
当前路径下保存了log文件,reader可以从该文件解析出数据原来的内容。
编写reader.cpp
|
|
编译&运行
|
|
可见reader成功从log文件解析出message。
本文介绍了Google Protocol Buffer,一种轻便高效的结构化数据存储格式,适用于数据串行化和RPC数据交换。主要内容包括ProtoBuf的简介、入门步骤、字段规则(required、optional、repeated)的解释,以及如何编译.proto文件并编写读写程序。

4148

被折叠的 条评论
为什么被折叠?



