Protobuf 是 Google 开发的语言中立、平台中立的结构化数据序列化和反序列化协议。用于应用程序间结构化数据的传输,相对于JSON、XML等基于文本的协议,它以二进制方式传输数据,效率更高。
有关 protobuf 详细介绍请参见官方文档 Protocol Buffers Documentation
在实际使用中发现官方文档对消息体中各种不同类型数据的构建和解析没有特别详细的说明,特别是复杂数据。本文分享在实际使用中的经验,抛砖引玉,希望对大家会有所帮助。
以下的示例均以Python语言为例来说明。
基本数据类型列表
下面的示例基于官方文档中包含的 helloword例子修改。用户信息 UserInfo 包括用户名、用户ID和组ID列表,其中组ID列表就是基本数据类型 int32 的列表。
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message UserInfo {
string name = 1;
int32 uid = 2;
repeated int32 gid = 3;
}
message HelloRequest {
UserInfo user = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
构建方式如下所示:
from __future__ import print_function
import os
import logging
import getpass
import grpc
i