- Protocol Buffers 教程
- Protocol Buffers - 首頁
- Protocol Buffers - 簡介
- Protocol Buffers - 基本應用
- Protocol Buffers - 結構
- Protocol Buffers - 訊息
- Protocol Buffers - 字串
- Protocol Buffers - 數字
- Protocol Buffers - 布林值
- Protocol Buffers - 列舉
- Protocol Buffers - 重複欄位
- Protocol Buffers - 對映
- Protocol Buffers - 巢狀類
- Protocol Buffers - 可選欄位和預設值
- Protocol Buffers - 語言無關性
- Protocol Buffers - 複合資料型別
- Protocol Buffers - 命令列用法
- Protocol Buffers - 更新定義規則
- Protocol Buffers - 與 Kafka 整合
- Protocol Buffers - 在其他語言中的使用
- Protocol Buffers 有用資源
- Protocol Buffers - 快速指南
- Protocol Buffers - 有用資源
- Protocol Buffers - 討論
Protocol Buffers - 訊息
概述
Protocol Buffers 的最基本構建塊是message屬性。這在我們使用的語言(例如 Java、Python 等)中轉換為類。
示例程式碼
以下是指示 Protocol Buffers 建立給定類例項所需的語法:
syntax = "proto3";
package theater;
option java_package = "com.tutorialspoint.theater";
message Theater {
}
我們將以上內容儲存到“theater.proto”檔案中,並在探索其他資料結構時使用它。
解釋
這裡的“syntax”表示我們使用的是哪個版本的 Protocol Buffers。因此,我們使用的是最新版本 3,該模式可以使用所有對版本 3 有效的語法。
syntax = "proto3";
這裡的包用於衝突解決,例如,如果我們有多個同名的類/訊息。
package tutorial;
此引數特定於 Java,即從“.proto”檔案自動生成的程式碼所在的包。
option java_package = "com.tutorialspoint.greeting";
現在我們完成了先決條件,這裡最後一項是:
message Theater
這僅僅是將要建立/重新建立的物件的基類的類名。請注意,它在當前形式下毫無用處,因為它沒有任何其他屬性。但隨著我們的繼續,我們將新增更多屬性。
使用多個訊息屬性
單個 proto 檔案也可以包含多個類/訊息。例如,如果我們想,我們也可以在同一個檔案中新增一個Visitors訊息/類。Protocol Buffers 將確保為此建立兩個獨立的類。例如:
syntax = "proto3";
package theater;
option java_package = "com.tutorialspoint.theater";
message Theater {
}
message Visitor {
}
從 proto 檔案建立 Java 類
要使用 Protocol Buffers,我們現在必須使用protoc二進位制檔案從此“.proto”檔案建立所需的類。讓我們看看如何做到這一點:
protoc --java_out=. proto_files\theater.proto
使用從 proto 檔案建立的 Java 類
就是這樣!上述命令應該在當前目錄中建立所需的檔案,現在我們可以在 Java 程式碼中使用它們:
Theater theater = Theater.newBuilder().build() Visitor visitor = Visitor.newBuilder().build()
在這個階段,它並不是很有用,因為我們還沒有向成員/類新增任何屬性。當我們在Protocol Buffers - 字串章節中檢視字串時,我們將這樣做。
廣告