Protocol Buf 版本 : 3.10.0java
Protocol Buf 是谷歌出品的一種序列化通信協議,以高效和跨平臺著稱。同時理解起來也很晦澀,且中文文檔不齊全,不一樣版本的協議之間兼容性較差。本文從應用的角度聊一下如何在 java 項目中使用該協議。git
首先須要理解,使用 Protocol Buf 的流程是:github
[1] 編寫 proto 文件 [2] 編譯 proto 文件成 java 類 [3] 在 java 項目中以 Builder 方式調用類的構造器
首先須要下載相應操做系統平臺的解析工具 github[https://github.com/protocolbu...]
在 Win10 上,cmd 執行:shell
d:\\protoc --java_out=d:\\Message.proto
上述例子中 protoc.exe 被放置在 d 盤下,proto 文件名稱叫 Message.proto,也放在 d 盤下。
Linux 和 MacOs 下的命令和 Win10 差很少:工具
./protoc --java_out=./Message.proto
編譯結束後會在指定路徑下出現一個 .java 文件,具體路徑在 proto 中配置。ui
// 指定協議 syntax = "proto3"; // 指定包名 package cn.mikylin.proto3.test; // 指定 java 包路徑 option java_package = "cn.mikylin.proto3"; // 指定 java class 名稱,不能夠與 message 名稱重複 option java_outer_classname = "MessageTest"; // 引入谷歌編寫的 any.proto;any 能夠包裝任意類型的數據 // 須要到 github 上把 any.proto 下載到和當前 proto 同一個目錄下 // import "google/protobuf/any.proto"; /* message 內是 protobuf 的消息主體部分, 能夠簡單理解爲一個 java bean。 修飾詞: singular - 能夠不存在(非必填惟一項),默認修飾詞,無需填寫(填寫則會報錯) repeated - 能夠不存在或屢次(非必填可多項),默認值空 reserved - 保留字段,不被使用 數據類型: int64 / unit64 - 對應 java 的 long,默認 0 int32 / unit32 - 對應 java 的 int,默認 0 string - 對應 java 的 string,默認空字符串 float - 對應 java 的 float,默認 0 double - 對應 java 的 double,默認 0 bool - 對應 java 的 boolean,默認 false bytes - 對應 java 的 byteString */ message Test { int64 test_1 = 1; string test_2 = 2; int32 test_3 = 3; repeated int64 test_4 = 4; // message 內部能夠定義其它 message // 須要注意的是,message 裏的參數名和外面的不能重複 message Test_Inner_Message { int64 test_inner_1 = 1; string test_inner_2 = 2; repeated int32 test_inner_3 = 3; } Test_Inner_Message test_5 = 5; // 枚舉是一種自定義的有限集合的類型 enum TEST_ENUM { TEST_ENUM_0 = 0; TEST_ENUM_1 = 1; TEST_ENUM_2 = 2; } repeated TEST_ENUM test_6 = 6; reserved "foo", "bar"; // string foo = 6; // 此處會報錯,由於 foo 已是保留字段了 // oneof 修飾的數據,當其中一個存在值的時候,另外一個置空 oneof Test_Oneof { string test_oneof_1 = 7; int32 test_oneof_2 = 8; } // Any 類型的參數必須 // google.protobuf.Any data = 8; }
public static void main(String[] args) { MessageTest.Test build = MessageTest.Test .newBuilder() .setTest1(11L) .setTest2("2333") .setTest5( MessageTest .Test .Test_Inner_Message .newBuilder() .setTestInner2("2333333") .build() ) .build(); System.out.println(build.getTest1()); }