最近分析hbase源码,其中用到google protobuf来作为消息传递,所以想学习一下这工具的用法。
首先,先将一些有用的资料做个笔记:
http://www.ibm.com/developerworks/cn/linux/l-cn-gpb/
https://code.google.com/p/protobuf/
http://blog.csdn.net/ciml/article/details/5753367
http://www.cppblog.com/woaidongmao/archive/2009/06/23/88391.aspx
先安装protobuf的编译器:
下载:https://code.google.com/p/protobuf/downloads/list
sudo ./configure
sudo make
sudo make check
sudo make install
这里使用python进行演示(笔记方便),要使用python,还需要安装python模块
cd protobuf-2.5.0/python
sudo python setup.py build
sudo python setup.py test
sudo python setup.py install
安装完之后,先写一个proto文件,通过这个文件定义消息的格式
package test;
message helloworld
{
required int32 id=1;
required string str=2;
optional int32 opt=3;
}
这里消息的格式如下:
两个int型:id 和 optional, 一个字符串型:str
生成python模块:
protoc --python_out=out ./helloword.proto
编写python 脚本读写消息:
#!/usr/bin/python
import helloword_pb2
import sys
def write():
hw = helloword_pb2.helloworld()
hw.id = 123
hw.str = "hello world"
hw.opt = 456
hw_str = hw.SerializeToString()
#print hw_str
hw2 = helloword_pb2.helloworld()
hw2.ParseFromString(hw_str)
print "id: "+str(hw2.id)
print "str: "+hw2.str
print "opt: "+str(hw2.opt)
if __name__ == "__main__":
write()