Protocol Buffers 學習(5):在 rpc 中使用 protobuf

Protocol buffers的一個重要應用就是RPC服務,下面簡單介紹一下相關的使用方法javascript

定義服務

若是要使用RPC(遠程過程調用)系統的消息類型,能夠在.proto文件中定義一個RPC服務接口,protocol buffer編譯器將根據您選擇的語言生成服務接口代碼和存根(記錄)。 例如,若是要使用一個使用SearchRequest並返回SearchResponse的方法定義RPC服務,能夠在.proto文件中定義它,以下所示:java

service SearchService {
  rpc Search (SearchRequest) returns (SearchResponse);
}複製代碼

目前比較典型的使用protocol buffer的RPC是google的gRPCgit

JSON 映射

Proto3 支持JSON的規範編碼,這使得不一樣系統之間共享數據更容易json

若是在JSON編碼中數據缺乏值或者值爲空,protocol buffer解析時會解析成字段的默認值app

proto3 JSON JSON 例子 說明
message object {"fBar": v, "g": null, …} Generates JSON objects. Message field names are mapped to lowerCamelCase and become JSON object keys. null is accepted and treated as the default value of the corresponding field type.
enum string "FOO_BAR" The name of the enum value as specified in proto is used.
map object {"k": v, …} All keys are converted to strings.
repeated V array [v, …] null is accepted as the empty list [].
bool true, false true, false
string string "Hello World!"
bytes base64 string "YWJjMTIzIT8kKiYoKSctPUB+"
int32, fixed32, uint32 number 1, -10, 0 JSON value will be a decimal number. Either numbers or strings are accepted.
int64, fixed64, uint64 string "1", "-10" JSON value will be a decimal string. Either numbers or strings are accepted.
float, double number 1.1, -10.0, 0, "NaN", "Infinity" JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". Either numbers or strings are accepted. Exponent notation is also accepted.
Any object {"@type": "url", "f": v, … } If the Any contains a value that has a special JSON mapping, it will be converted as follows: {"@type": xxx, "value": yyy}. Otherwise, the value will be converted into a JSON object, and the "@type" field will be inserted to indicate the actual data type.
Timestamp string "1972-01-01T10:00:20.021Z" Uses RFC 3339, where generated output will always be Z-normalized and uses 0, 3, 6 or 9 fractional digits.
Duration string "1.000340012s", "1s" Generated output always contains 0, 3, 6, or 9 fractional digits, depending on required precision. Accepted are any fractional digits (also none) as long as they fit into nano-seconds precision.
Struct object { … } Any JSON object. See struct.proto.
Wrapper types various types 2, "2", "foo", true, "true", null, 0, … Wrappers use the same representation in JSON as the wrapped primitive type, except that null is allowed and preserved during data conversion and transfer.
FieldMask string "f.fooBar,h" See fieldmask.proto.
ListValue array [foo, bar, …]
Value value Any JSON value
NullValue null JSON null
相關文章
相關標籤/搜索