protobuf示例

简介: Google protobuf 是一个高性能的序列化结构化数据存储格式的接口描述语言,具有多语言支持,协议数据小,方便传输,高性能等特点。通过将结构化数据序列化(串行化)成二进制数组,并将二进制数组反序列化成数据对象。

Google protobuf 是一个高性能的序列化结构化数据存储格式的接口描述语言,具有多语言支持,协议数据小,方便传输,高性能等特点。通过将结构化数据序列化(串行化)成二进制数组,并将二进制数组反序列化成数据对象。用于取代JSONXML,作为服务器通信协议。google 将protobuf协议用于 RPC 系统和持续数据存储系统。Protobuf 的主要优点就是:简单,快。

1.首先我们需要编写一个 proto 文件,定义我们程序中需要处理的结构化数据,在 protobuf 的术语中,结构化数据被称为 Messageproto 文件非常类似 java 或者 C 语言的数据定义。

package lm;

message helloworld

{

required int32     id = 1;  // ID

required string    str = 2;  // str

optional int32     opt = 3;  //optional field

}

2.编译

protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto

3.应用示例

writer-写入磁盘

#include "lm.helloworld.pb.h"

int main(void)

{

lm::helloworld msg1;

msg1.set_id(101);

msg1.set_str(“hello);

// Write the new address book back to disk.

fstream output("./log", ios::out | ios::trunc | ios::binary);

if (!msg1.SerializeToOstream(&output))

{

cerr << "Failed to write msg." << endl;

return -1;

}        

return 0;

}

reader-从磁盘读入

#include "lm.helloworld.pb.h"

void ListMsg(const lm::helloworld & msg) {

cout << msg.id() << endl;

cout << msg.str() << endl;

}

int main(int argc, char* argv[]) {

lm::helloworld msg1;

{

fstream input("./log", ios::in | ios::binary);

if (!msg1.ParseFromIstream(&input)) {

cerr << "Failed to parse address book." << endl;

return -1;

}

}

ListMsg(msg1);

}

5.缺点

Protbuf 与 XML 相比也有不足之处。它功能简单,无法用来表示复杂的概念。XML 已经成为多种行业标准的编写工具,Protobuf 只是 Google 公司内部使用的   工具,在通用性上还差很多。

由于文本并不适合用来描述数据结构,所以 Protobuf 也不适合用来对基于文本的标记文档(如 HTML)建模。另外,由于 XML 具有某种程度上的自解释性,它可以被人直接读取编辑,在这一点上 Protobuf 不行,它以二进制的方式存储,除非你有 .proto 定义,否则你没法直接读出 Protobuf 的任何内容

原文

java使用示例

http://blog.csdn.net/lovexiaozeng336/article/details/8187519

http://www.ibm.com/developerworks/cn/linux/l-cn-gpb/

https://code.google.com/p/thrift-protobuf-compare/wiki/Benchmarking

目录
相关文章
|
7月前
|
编解码 Java 编译器
【Protobuf】Protobuf中的Message语法规范
在Message中定义一个或者多个字段,FieldType是字段的数据类型,可以是基本类型(如int32、string、bool等)或其他定义的Message类型。fieldName是字段的名称,可以根据需求自定义。fieldNumber是字段的唯一标识号,用于在消息的二进制编码中标识字段。
159 0
|
7月前
|
JSON Go 数据格式
Golang 语言中怎么解码 4 种常见JSON 格式数据?
Golang 语言中怎么解码 4 种常见JSON 格式数据?
33 0
|
4天前
|
存储 Java Go
|
4天前
|
JSON 数据格式
protobuf与json相互转换的方法
protobuf与json相互转换的方法
56 0
|
6月前
|
C++ 容器
使用protobuf的简单流程记录、编译protobuf时遇到的坑 以及 链接protobuf的坑
使用protobuf的简单流程记录、编译protobuf时遇到的坑 以及 链接protobuf的坑
|
6月前
|
JSON Linux 测试技术
go语言处理数据、基本通信以及环境配置 -- json,protobuf,grpc
go语言处理数据、基本通信以及环境配置 -- json,protobuf,grpc
|
6月前
|
存储
protobuf中的Base 128 Varints类型分析
protobuf中的Base 128 Varints类型分析
51 0
|
7月前
|
XML JSON Java
Protobuf 语法详解
Protobuf 语法详解
109 0
|
JSON Go 数据格式
Golang 处理复杂格式JSON数据(多类型混合)
Golang 处理复杂格式JSON数据(多类型混合)
267 0
|
JSON Go 数据格式
Golang JSON的编码和解析
Golang JSON的编码和解析
127 0