我需要对字节流中的一系列协议缓冲区消息进行序列化和反序列化.有一些预定的消息类型.编码类型信息的推荐方法是什么,以便我的应用程序可以知道它应该读取哪种类型?
最常见的方法是使用union消息.
例如:
message AnyMessage {
optional Message1 msg1 = 1;
optional Message2 msg2 = 2;
...
}
Run Code Online (Sandbox Code Playgroud)
然后,所有消息都在AnyMessage容器内编码/解码.从protobuf 2.6开始,您还可以使用说明oneof符,该说明符将确保仅设置其中一个子消息.
我的建议(排名不分先后)是:
使用自我描述消息(位于页面底部)。在这种情况下,您可以
保持原始名称较小并在文件名中使用原始名称,例如
salesProto_Store001.bin
这有几个好处:
支持自描述消息,其中
具有搜索功能,它将尝试将Protobuf 消息中的字段与已知的Proto 定义文件进行匹配,并为您提供可能的匹配项
背景: 如果您不知道,protocol buffers proto 文件可以转换为FileDescriptorSet protocol 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;
}
Run Code Online (Sandbox Code Playgroud)