Protocol Buffers( 简称 Protobuf)是一种高效的可扩展的结构化数据存储方式,非常适合做数据存储和RPC数据交换。Protocol Buffers是开源项目,由Google发布,Google内部的几乎所有的RPC协议和文件格式都使用Protocol Buffers。
一般都会提到Protobuf和XML的比较,Protobuf 以高效的二进制方式存储,比 XML 小 3 到 10 倍,快 20 到 100 倍,语义更清晰,无需类似 XML 解析器的东西。这就使得Protobuf可以作为XML的替代。而且,Protobuf以二进制方式存储,如果没有.proto文件,是无法读出它的任何 内容,使用它在网络上传输数据时有一定的保密性。
Protobuf开源项目的主页:http://code.google.com/p/protobuf/
API参考文档的主页:http://code.google.com/apis/protocolbuffers/
我看了这个项目半天也没看出个头绪来,还是从简单的例子先开始学习如何使用Protobuf。
下面介绍基于Unix/Linux平台。
安装:
从这个网址http://code.google.com/p/protobuf/downloads/list下载Protobuf的源代码。目前最新版本是2.4.1,如果上面的链接无效的话,可以点此下载。
下载完成后,按照一下步骤安装:
tar –xzf protobuf-2.4.1.tar.gz
cd protobuf-2.4.1
./configure
make
make check
make install
我是在Ubuntu下安装的,最后一步需要管理员权限,sudo make install。
安装完成之后,运行一下 protoc –version 来验证是否已经安装成功。如果出现lib找不到之类的错误,运行一下如下命令
export LD_LIBRARY_PATH=$LD_LIBRARYY_PATH:/usr/local/lib
一个简单的例子:
下面介绍一个简单的例子来学习如何使用Protobuf。点此下载示例代码。这个示例代码参考这篇文章,只做了简单的修改。
首先编辑helloworld.proto文件,这个文件定义了数据存储结构。
package lm; message helloworld { required int32 id = 1 ; required string str = 2 ; optional int32 opt = 3 ; }
这里定义了两个必须的变量,一个int型变量id,一个字符串str。
我们运行如下命令
protoc –cpp_out=. helloworld.proto
生成两个文件:helloworld.pb.h 和 helloworld.pb.cpp 。这两个文件就是用来操作.proto文件定义的数据的源代码。
下面我们用Protobuf写一个文件,然后再把它读出来。
write.cpp
#include "helloworld.pb.h" #include <iostream> #include <fstream> using namespace std; int main(void) { lm::helloworld msg1; msg1.set_id(101); msg1.set_str("hello protocol buffers"); fstream output("./log",ios::out|ios::trunc|ios::binary); msg1.SerializeToOstream(&output); return 0; }
定义了结构msg1,设置好id和str后,用SerializeToOstream来序列化,写入文件log中
read.cpp
#include "helloworld.pb.h" #include <iostream> #include <fstream> using namespace std; int main(void) { lm::helloworld msg1; fstream input("./log", ios::in | ios::binary); msg1.ParseFromIstream(&input); cout << "id = " << msg1.id() << endl; cout << "str = " << msg1.str() << endl; return 0; }
使用ParseFromIstream就可以把log的文件读取到msg1中
上面给出了这个示例的代码下载,下载完代码后,运行
tar –xzf myexample.tar.gz
cd myexample
make
./write
./read
结果如下:
id = 101
str = hello protocol buffers
从这个简单的例子可以看出,Protobuf的使用比起XML简洁的多。
浙公网安备 33010602011771号