【发布时间】:2014-09-25 21:59:00
【问题描述】:
我需要序列化和反序列化一系列协议缓冲区消息到字节流和从字节流输出。有一些预先确定的消息类型。编码类型信息的推荐方法是什么,以便我的应用程序可以知道它应该读取哪种类型?
【问题讨论】:
-
协议缓冲区是序列化的结构化数据。您能解释一下为什么您认为需要对序列化数据进行编码吗?
标签: protocol-buffers
我需要序列化和反序列化一系列协议缓冲区消息到字节流和从字节流输出。有一些预先确定的消息类型。编码类型信息的推荐方法是什么,以便我的应用程序可以知道它应该读取哪种类型?
【问题讨论】:
标签: protocol-buffers
最常用的方法是使用union message。
例如:
message AnyMessage {
optional Message1 msg1 = 1;
optional Message2 msg2 = 2;
...
}
然后所有消息都在AnyMessage 容器内进行编码/解码。从 protobuf 2.6 开始,您还可以使用 oneof 说明符,这将确保只设置一个子消息。
【讨论】:
我的建议不分先后:
使用self describing message(在页面底部)。在这种情况下,您可以
保持 proto 名称较小,并在文件名中使用 proto-name,例如
salesProto_Store001.bin
这有几个好处:
支持自我描述消息
有一个搜索功能,它将尝试将 Protobuf 消息中的 字段 与已知的 Proto 定义 文件进行匹配,并为您提供可能匹配的
背景: 如果您不知道,protocol buffers proto 文件可以转换为FileDescriptorSetprotocol buffer 消息 并存储
自我描述信息:
message SelfDescribingMessage {
// Set of .proto files which define the type.
required FileDescriptorSet proto_files = 1;
// Name of the message type. Must be defined by one of the files in
// proto_files.
required string type_name = 2;
// The message data.
required bytes message_data = 3;
}
【讨论】: