protobuf的简单使用

操作系统 : CentOS7.3.1611_x64

gcc版本 :4.8.5

go 版本 : go1.8.3 linux/amd64

Python 版本 : 2.7.5

libprotoc : 2.5.0

Protobuf是Google开发一种数据描述语言,能够将结构化数据序列化,可用于数据存储、通信协议等方面。

首页: https://developers.google.com/protocol-buffers/

文档: https://developers.google.com/protocol-buffers/docs/overview

github地址: https://github.com/google/protobuf

这里记录了C++、Go和Python语言的简单使用示例,更多内容请参考官网手册。

准备工作

安装protobuf:

yum install protobuf protobuf-compiler protobuf-c-devel protobuf-devel

写proto文件(addr.book.proto):

package addr;
message book
{
   required int32     id = 1;
   required string    str = 2;
   optional int32     opt = 3;
}

C++示例

写文件操作(writer.cpp):

https://github.com/mike-zhang/cppExamples/blob/master/protobufOpt/example1/writer.cpp

读文件操作(reader.cpp):

https://github.com/mike-zhang/cppExamples/blob/master/protobufOpt/example1/reader.cpp

Makefile文件:

CC = g++
CFLAGS = -g -O2 -Wall
SRC_DIR=.
DST_DIR=libs

all:
    make genproto
    make writer
    make reader

genproto:
    mkdir -p $(DST_DIR)
    protoc -I=$(SRC_DIR) --cpp_out=$(DST_DIR) addr.book.proto

writer:
    $(CC) -o writer writer.cpp $(DST_DIR)/addr.book.pb.cc -I$(DST_DIR) -lprotobuf

reader:
    $(CC) -o reader reader.cpp $(DST_DIR)/addr.book.pb.cc -I$(DST_DIR) -lprotobuf

clean:
    rm -rf $(DST_DIR)
    rm -f writer reader log
    rm -f *.o

运行效果:

[root@localhost proto1]# ./writer
[root@localhost proto1]# ./reader
101
book1
[root@localhost proto1]#

Go示例代码

安装goprotobuf:

yum install golang-googlecode-goprotobuf.x86_64

将proto文件转换为go代码(genPbCode.sh):

#! /bin/sh

mkdir -p src/addr
protoc -I=. --go_out=src/addr addr.book.proto

修改protobuf路径:

vi src/addr/addr.book.pb.go

import proto "code.google.com/p/goprotobuf/proto"

修改为:

import proto "github.com/golang/protobuf/proto"

添加PATH(临时使用时可以这么操作):

export GOPATH=$GOPATH:$PWD

写文件操作(write.go):

https://github.com/mike-zhang/goExamples/blob/master/protobufOpt/protoTest1/write.go

读文件操作(reader.go):

https://github.com/mike-zhang/goExamples/blob/master/protobufOpt/protoTest1/read.go

运行效果:

[root@localhost proto3]# go run write.go
[root@localhost proto3]# go run read.go
id:11 str:"testMsg11"
[root@localhost proto3]#

Python示例

需要安装protobuf包:

pip install protobuf

将proto文件转换为python代码(genPbCode.sh):

#! /bin/sh

protoc -I=. --python_out=. addr.book.proto
touch addr/__init__.py

写文件操作(write.py):

https://github.com/mike-zhang/pyExamples/blob/master/protobufOpt/example1/write.py

读文件操作(reader.py):

https://github.com/mike-zhang/pyExamples/blob/master/protobufOpt/example1/reader.py

运行效果:

(py27env) [root@localhost proto2]# ./genPbCode.sh
(py27env) [root@localhost proto2]# python write.py
(py27env) [root@localhost proto2]# python reader.py
id: 1
str: "testMsg1"

(py27env) [root@localhost proto2]#

好,就这些了,希望对你有帮助。

本文github地址:

https://github.com/mike-zhang/mikeBlogEssays/blob/master/2018/20180201_protobuf的简单使用.rst

欢迎补充

原文地址:https://www.cnblogs.com/MikeZhang/p/protobufExample20180201.html