Protocol Buffers
Protocol Buffers 是一種語言中立、平台中立、可擴展的機制,用於序列化結構化資料。
什麼是 Protocol Buffers?
Protocol buffers 是 Google 的語言中立、平台中立、可擴展機制,用於序列化結構化資料 – 可以想像成 XML,但更小、更快、更簡單。您只需定義一次資料的結構,即可使用特殊的產生原始碼,輕鬆地將結構化資料寫入和讀取到各種資料流,並使用各種語言。
選擇您喜愛的語言
Protocol buffers 支援在 C++、C#、Dart、Go、Java、Kotlin、Objective-C、Python 和 Ruby 中產生程式碼。使用 proto3,您也可以使用 PHP。
範例實作
edition = "2023";
message Person {
string name = 1;
int32 id = 2;
string email = 3;
}
圖 1. Proto 定義。
// Java code
Person john = Person.newBuilder()
.setId(1234)
.setName("John Doe")
.setEmail("jdoe@example.com")
.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. 使用產生的類別來解析持久化資料。