.proto
做爲文件後綴,除結構定義以外的語句以分號結尾enum GenderType { SECRET = 0; FEMALE = 1; MALE = 2; } // 人 message Person { int64 id = 1; string name = 2; GenderType gender = 3; string number = 4; } 複製代碼
字段格式:限定修飾符 | 數據類型 | 字段名稱 | = | 字段編碼值 | [字段默認值]java
限定修飾符包含:required、optional、repeated數組
Protobuf定義了一套基本數據類型:markdown
Protobuf 數據類型 | 描述 | 打包 |
---|---|---|
bool | 布爾類型 | 1字節 |
double | 64位浮點數 | N |
float | 32位浮點數 | N |
int32 | 32位整數 | N |
uint32 | 無符號32位整數 | N |
int64 | 64位整數 | N |
uint64 | 64位無符號整數 | N |
$int32 | 32位整數,處理負數效率更高 | N |
$int64 | 64位整數,處理負數效率更高 | N |
fixed32 | 32位無符號整數 | 4 |
fixed64 | 64位無符號整數 | 8 |
$fixed32 | 32位整數,能以更高的效率處理負數 | 4 |
$fixed64 | 64位整數,能以更高的效率處理負數 | 8 |
string | 只能處理ASCII字符 | N |
bytes | 用於處理多字節的語言字符,如中文 | N |
enum | 能夠包含一個用戶自定義的枚舉類型uint32 | N(uiint32) |
message | 能夠包含一個用戶自定義的消息類型 | N |
.proto
文件中定義一個 RPC 服務接口,protocol buffer 編譯器會根據所選擇的不一樣語言生成服務接口代碼好比,想要定義一個 RPC 服務並具備一個方法,該方法接收 SearchRequest 並返回一個 SearchResponse,此時能夠在.proto
文件中進行以下定義:ui
service SearchService { rpc Search(SearchRequest) returns (SearchResponse) {} } 複製代碼
一個 .proto 文件中能夠定義多個消息類型,通常用於同時定義多個相關的消息,例如在同一個 .proto 文件中同時定義搜索請求和響應消息:編碼
syntax = "proto3" // 聲明使用的 protobuf 版本 message SearchRequest { string query = 1; // 查詢字符串 int32 page_number = 2; int32 result_per_page = 3; } message SearchResponse { } 複製代碼
message 支持嵌套使用,做爲另外一個 message 中的字段類型url
message SearchResponse { repeated Result results = 1; } message Result { string url = 1; string title = 2; repeated string snippets = 3; } 複製代碼
支持嵌套消息,消息能夠包含另外一個消息做爲字段。也能夠在消息內定義一個新的消息。spa
內部聲明的 message 類型名稱只可在內部直接使用:code
message SearchResponse { message Result { string url = 1; string title = 2; repeated string snippets = 3; } repeated Result results = 1; } 複製代碼
另外,還能夠多層嵌套:orm
message Outer { message A { message Inner { int64 ival = 1; bool booly = 2; } } message B { message Inner { int64 ival = 1; bool booly = 2; } } } 複製代碼
proto3 支持 map 類型聲明接口
鍵、值類型能夠是內置類型,也能夠是自定義 message 類型
字段不支持 repeated 屬性
map<key_type, value_type>map_field = N; message Project {...} map<string, Project>projects = 1; 複製代碼
能夠使用 import 語句導入使用其它描述文件中聲明的類型
protobuf 接口文件能夠經過 import 導入須要的文件,例如: import "example.proto"
protobuf 編譯器會在 -I/ --proto_path 參數指定的目錄中查找導入的文件,若是沒有指定該參數,默認在當前目錄中查找
在 proto 文件中使用 package 聲明包名,避免命名衝突:
syntax = "proto3" package foo.bar message Open {...} 複製代碼
在其餘的消息格式定義中能夠使用包名 + 消息名的方式來使用類型,如:
message Foo { ... foo.bar.Open open = 1; ... } 複製代碼
在不一樣的語言中,包名定義對編譯後生成的代碼影響不一樣: