Protobuf 與 Interface 的比較
本文比較兩種 IDL,Protobuf 和 Interface 的差異,幫助 Dubbo 協定開發者理解 Protobuf,並為後續轉移到 Triple 協定和 Grpc 協定鋪路。
1. 資料類型
1.1. 基本類型
proto 類型 | Java 類型 |
---|---|
double | double |
float | float |
int32 | int |
int64 | long |
uint32 | int[註] |
uint64 | long[註] |
sint32 | int |
sint64 | long |
fixed32 | int[註] |
fixed64 | long[註] |
sfixed32 | int |
sfixed64 | long |
bool | boolean |
string | String |
bytes | ByteString |
[註] 在 Java 中,無符號 32 位元和 64 位元整數使用它們的有符號對數表示,最高位元僅儲存在符號位元中。
2. 複合類型
2.1. 列舉
- 原始 pb 程式碼
enum TrafficLightColor {
TRAFFIC_LIGHT_COLOR_INVALID = 0;
TRAFFIC_LIGHT_COLOR_UNSET = 1;
TRAFFIC_LIGHT_COLOR_GREEN = 2;
TRAFFIC_LIGHT_COLOR_YELLOW = 3;
TRAFFIC_LIGHT_COLOR_RED = 4;
}
- 產生的 Java 程式碼
列舉是常數,因此使用大寫
2.2. 陣列
- 原始 pb 程式碼
message VipIDToRidReq {
repeated uint32 vipID = 1;
}
- 產生的 Java 程式碼
底層實際上是 ArrayList
2.3. 集合
PB 不支援無序且不重複的集合,只能借用陣列來實現
,並且需要自行去除重複元素
。
2.4. 字典
- 原始 pb 程式碼
message BatchOnlineRes {
map<uint32, uint32> onlineMap = 1;//online status
}
- 產生的 Java 程式碼
2.5. 巢狀
- 原始 pb 程式碼
message BatchAnchorInfoRes {
map<uint32, AnchorInfo> list = 1; //user information map list
}
/*
* The function of the corresponding interface: get user information in batches or individually
*/
message AnchorInfo {
uint32 ownerUid = 1 [json_name="uid"]; //user id
string nickName = 2 [json_name="nn"]; //User nickname
string smallAvatar = 3 [json_name="savt"]; //full path of user avatar - small
string middleAvatar = 4 [json_name="mavt"]; //Full path of user avatar - middle
string bigAvatar = 5 [json_name="bavt"]; //Full path of user avatar - big
string avatar = 6 [json_name="avt"]; //User avatar
}
- 產生的 Java 程式碼
3. 欄位預設值
- 對於字串,預設值是空字串。
- 對於位元組,預設值是空位元組。
- 對於布林值,預設值是 false。
- 對於數值類型,預設值是零。
- 對於列舉類型 (enum),預設值為第一個定義的列舉值,且其值必須為 0。
- 對於訊息欄位,該欄位未設定。其確切值取決於程式語言。詳情請參閱產生的程式碼指南。
4. 整體架構
特性 | Java 介面 | Protobuf | 備註 |
---|---|---|---|
方法重載 | √ | × | |
泛型/模板 | √ | × | |
方法繼承 | √ | × | |
巢狀定義 | √ | 部分支援 | PB 僅支援訊息和列舉類型的巢狀定義 |
導入檔案 | √ | √ | |
欄位為 null | √ | × | |
多個輸入參數 | √ | × | PB 僅支援單個輸入參數 |
0 個輸入參數 | √ | × | PB 必須有輸入參數 |
0 個輸出參數 | √ | × | PB 必須有輸出參數 |
輸入/輸出參數為抽象類別 | √ | × | PB 的輸入/輸出參數必須為具體類別 |
輸入/輸出參數為介面 | √ | × | PB 的輸入/輸出參數必須為具體類型 |
輸入參數/輸出參數為基本類型 | √ | × | PB 的輸入參數/輸出參數必須為結構 |
5. 社群概況
- 社群首頁地址:https://developers.google.cn/protocol-buffers/
- 社群開源地址:https://github.com/google/protobuf
- 相關 Jar 的 Maven:https://search.maven.org/search?q=com.google.protobuf
上次修改日期:2023 年 1 月 2 日:增強英文文件 (#1798) (95a9f4f6c1c)