- 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 - 命令列使用
概述
Protobuf 將資料序列化並以二進位制格式儲存。如果我們只是處理字串,這可能不是問題,因為最終 Protobuf 使用 UTF-8。因此,如果使用支援 UTF8 的閱讀器,它儲存的任何文字都是人類可讀的。但是,諸如int32、布林值、列表、對映之類的內容使用特定的技術進行編碼以減少空間消耗。
因此,有時透過簡單的命令列實用程式對訊息進行編碼/解碼對於測試目的很有用。讓我們看看它是如何工作的 -
假設我們使用以下簡單的“greeting_cli.proto” -
syntax = "proto3";
package tutorial;
option java_package = "com.tutorialspoint.greeting";
message Greet {
string greeting = 1;
string username = 2;
int32 age = 3;
}
並且我們在cli_greeting_message中建立一條訊息 -
greeting: "Yo" username : "John" age : 50
現在,讓我們使用 Protobuf CLI 工具對這條訊息進行編碼 -
cat .\cli_greeting_msg.proto | protoc --encode=tutorial.Greet .\greeting_cli.proto > encoded_greeting
如果我們檢視此檔案內部的內容或cat此檔案 -
cat .\encoded_greeting ☻Yo↕♦John↑2
您會注意到除了“Yo”和“John”之外的一些奇怪字元。這是因為這些編碼可能不是有效的 Unicode/UTF-8 編碼。一般來說,UTF-8 是大多數地方使用的東西。在 Protobuf 的情況下,這用於字串,但整數、對映、布林值、列表具有單獨的格式。此外,此檔案還包含資料的元資料。
因此,我們需要一個解碼器/反序列化器來讀取此資料。讓我們使用它。
cat .\encoded_greeting | protoc --decode=tutorial.Greet .\greeting_cli.proto greeting: "Yo" username : "John" age : 50
因此,正如我們所看到的,我們能夠獲取已序列化並在檔案中看起來很奇怪的資料。
廣告