google protobuf 编程学习

最近分析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()






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值