Protocol Buffers practice

Due to the recent need for gRPC for use, we should first look at PB-related knowledge. Knowledge and practices related to the Python version of comb here for everyone.
I recommend a very detailed study addresses the link, if you need an in-depth study Click here

Brief introduction

Protocol Buffers hereinafter referred pb, google is developed that can serialize deserialize object data exchange format, like xml, but more than xml lighter, faster and easier. And as more focused and a cross-platform, and xml json data such as serialization, cross-platform cross-language.
It is a language-independent, platform-independent, scalable structured data sequence scheme for the communication protocol, data storage and other additional uses.

installation

1.github:https://github.com/google/protobuf/releases 下载最新版本的对应语言的pb
2.下载完毕之后运行包中自带config文件。
3.make&&make install。
4.进入python文件夹 
5.运行安装命令
>   python setup.py build
>   python setup.py test

use

PB is used to define a .proto file which defines the number of data types and formats. Here I will no longer carry the corresponding field in each language, as these official documents are written very clearly. Here direct the easiest to use.

syntax = "proto3";

package people;

message Person {
    string name = 1;
    int32 id = 2;
    enum Gender {     //定义枚举类型,每个枚举定义必须包含一个映射到0的常量作为它的第一个元素
        FEMALE = 0;
        MALE = 1;
    }
    Gender gender = 3;

    enum PhoneType {    //定义枚举类型,每个枚举定义必须包含一个映射到0的常量作为它的第一个元素
        MOBILE = 0;
        HOME = 1;
        WORK = 2;
    }

    message PhoneNumber {     //定义嵌套消息类型
        string number = 1;
        PhoneType type = 2;
    }
    repeated PhoneNumber phones = 4;      //动态数组
}

Compile

Python命令:
protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/people.proto
生成一个people_pb2.py文件

C++命令:
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/ people.proto
生成people.pb.h和people.pb.cc文件

Java命令:
protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/ people.proto
每个message生成一个.java文件

Python+PB

from test_pb2 import Person

person = Person()

person.name = "xx.xxx"
person.id = 123456
person.gender = 1

phone = person.phones.add()
phone.number = "654321"
phone.type = 2
result = person.SerializeToString()

print(person)
print(result)

Results are as follows

$ python3 main.py 

name: "xx.xxx"
id: 123456
gender: MALE
phones {
  number: "654321"
  type: WORK
}

b'\n\x06xx.xxx\x10\xc0\xc4\x07\x18\x01"\n\n\x06654321\x10\x02'

Guess you like

Origin blog.51cto.com/13384175/2407494