Protocol Buffers
Protocol Buffers 是一种与语言无关、与平台无关的可扩展机制,用于序列化结构化数据。
什么是 Protocol Buffers?
Protocol buffers 是 Google 的一种与语言无关、与平台无关、可扩展的机制,用于序列化结构化数据——可以将其视为 XML,但更小、更快、更简单。您只需定义一次数据结构,然后可以使用特殊生成的源代码轻松地将结构化数据写入和读取到各种数据流中,并使用各种语言。
选择你喜欢的语言
Protocol buffers 支持在 C++、C#、Dart、Go、Java、Kotlin、Objective-C、Python 和 Ruby 中生成代码。使用 proto3,您还可以使用 PHP。
示例实现
message Person {
optional string name = 1;
optional int32 id = 2;
optional string email = 3;
}
图 1. proto 定义。
// Java code
Person john = Person.newBuilder()
.setId(1234)
.setName("John Doe")
.setEmail("[email protected]")
.build();
output = new FileOutputStream(args[0]);
john.writeTo(output);
图 2. 使用生成的类来持久化数据。
// C++ code
Person john;
fstream input(argv[1],
ios::in | ios::binary);
john.ParseFromIstream(&input);
id = john.id();
name = john.name();
email = john.email();
图 3. 使用生成的类来解析持久化数据。