比較 gRPC 服務與 HTTP APICompare gRPC services with HTTP APIs

James 牛頓-王By James Newton-King

本文說明gRPC services與 HTTP api (包括 ASP.NET Core web api)之間的比較。This article explains how gRPC services compare to HTTP APIs (including ASP.NET Core web APIs). 用來為您的應用程式提供 API 的技術是一項重要的選擇,gRPC 提供與 HTTP Api 相較之下的獨特優點。The technology used to provide an API for your app is an important choice, and gRPC offers unique benefits compared to HTTP APIs. 本文討論 gRPC 的優點和缺點,並建議在其他技術上使用 gRPC 的案例。This article discusses the strengths and weaknesses of gRPC and recommends scenarios for using gRPC over other technologies.

高階比較High-level comparison

下表提供 gRPC 和 HTTP Api 與 JSON 之間功能的高階比較。The following table offers a high-level comparison of features between gRPC and HTTP APIs with JSON.

特殊功能Feature gRPCgRPC HTTP Api 與 JSONHTTP APIs with JSON
合約Contract 必要(protoRequired (.proto) 選擇性(OpenAPI)Optional (OpenAPI)
通訊協定Protocol HTTP/2HTTP/2 HTTPHTTP
承載Payload Protobuf (小型,二進位)Protobuf (small, binary) JSON (大型、人類可讀取)JSON (large, human readable)
PrescriptivenessPrescriptiveness 嚴格規格Strict specification 鬆動.Loose. 任何 HTTP 都是有效的。Any HTTP is valid.
StreamingStreaming 用戶端,伺服器,雙向Client, server, bi-directional 用戶端,伺服器Client, server
瀏覽器支援Browser support 否(需要 grpc-web)No (requires grpc-web) Yes
安全性Security 傳輸(TLS)Transport (TLS) 傳輸(TLS)Transport (TLS)
用戶端程式代碼產生Client code-generation Yes OpenAPI + 協力廠商工具OpenAPI + third-party tooling

gRPC 的優點gRPC strengths

效能Performance

gRPC 訊息會使用Protobuf序列化,這是一種有效率的二進位訊息格式。gRPC messages are serialized using Protobuf, an efficient binary message format. Protobuf 會非常快速地在伺服器和用戶端上序列化。Protobuf serializes very quickly on the server and client. 在小型訊息承載中 Protobuf 序列化結果,這在有限的頻寬案例(例如行動應用程式)中很重要。Protobuf serialization results in small message payloads, important in limited bandwidth scenarios like mobile apps.

gRPC 是針對 HTTP/2 所設計,這是一種可透過 HTTP 1.x 提供顯著效能優勢的 HTTP 主要修訂版:gRPC is designed for HTTP/2, a major revision of HTTP that provides significant performance benefits over HTTP 1.x:

  • 二進位框架和壓縮。Binary framing and compression. HTTP/2 通訊協定在傳送和接收時都是精簡且有效率的。HTTP/2 protocol is compact and efficient both in sending and receiving.
  • 透過單一 TCP 連線進行多個 HTTP/2 呼叫的多工處理。Multiplexing of multiple HTTP/2 calls over a single TCP connection. 多工化可避免行標頭封鎖Multiplexing eliminates head-of-line blocking.

程式碼產生Code generation

所有的 gRPC 架構都提供第一級的程式碼產生支援。All gRPC frameworks provide first-class support for code generation. GRPC 開發的核心檔案是定義 gRPC 服務和訊息合約的proto檔案。A core file to gRPC development is the .proto file, which defines the contract of gRPC services and messages. 在此檔案中,gRPC 架構會產生服務基類、訊息和完整用戶端的程式碼。From this file gRPC frameworks will code generate a service base class, messages, and a complete client.

藉由共用伺服器和用戶端之間的proto檔案,可以從端對端產生訊息和用戶端程式代碼。By sharing the .proto file between the server and client, messages and client code can be generated from end to end. 用戶端的程式碼產生不會在用戶端和伺服器上排除重複的訊息,並為您建立強型別用戶端。Code generation of the client eliminates duplication of messages on the client and server, and creates a strongly-typed client for you. 不需要撰寫用戶端,就能在具有許多服務的應用程式中節省大量的開發時間。Not having to write a client saves significant development time in applications with many services.

嚴格規格Strict specification

具有 JSON 的 HTTP API 的正式規格不存在。A formal specification for HTTP API with JSON doesn't exist. 開發人員會爭論 Url、HTTP 動詞命令和回應碼的最佳格式。Developers debate the best format of URLs, HTTP verbs, and response codes.

GRPC 規格規定了 gRPC 服務必須遵循的格式。The gRPC specification is prescriptive about the format a gRPC service must follow. gRPC 可排除爭論並節省開發人員的時間,因為 gRPC 在平臺和實現之間是一致的。gRPC eliminates debate and saves developer time because gRPC is consistent across platforms and implementations.

StreamingStreaming

HTTP/2 提供長時間即時通訊資料流程的基礎。HTTP/2 provides a foundation for long-lived, real-time communication streams. gRPC 提供透過 HTTP/2 進行串流的第一級支援。gRPC provides first-class support for streaming through HTTP/2.

GRPC 服務支援所有串流組合:A gRPC service supports all streaming combinations:

  • 一元(無串流)Unary (no streaming)
  • 伺服器對用戶端串流Server to client streaming
  • 用戶端對伺服器的串流處理Client to server streaming
  • 雙向串流Bi-directional streaming

期限/超時和取消Deadline/timeouts and cancellation

gRPC 可讓用戶端指定他們願意等待 RPC 完成的時間長度。gRPC allows clients to specify how long they are willing to wait for an RPC to complete. 期限會傳送至伺服器,而伺服器可以決定在超過期限時要採取的動作。The deadline is sent to the server, and the server can decide what action to take if it exceeds the deadline. 例如,伺服器可能會在超時時取消進行中的 gRPC/HTTP/資料庫要求。For example, the server might cancel in-progress gRPC/HTTP/database requests on timeout.

透過子 gRPC 呼叫來傳播期限和取消,有助於強制執行資源使用限制。Propagating the deadline and cancellation through child gRPC calls helps enforce resource usage limits.

gRPC 適用于下列案例:gRPC is well suited to the following scenarios:

  • 微服務– gRPC 是針對低延遲和高輸送量通訊所設計。Microservices – gRPC is designed for low latency and high throughput communication. gRPC 非常適合用於效率非常重要的輕量微服務。gRPC is great for lightweight microservices where efficiency is critical.
  • 點對點即時通訊– gRPC 有絕佳的雙向串流支援。Point-to-point real-time communication – gRPC has excellent support for bi-directional streaming. gRPC 服務可以即時推送訊息,而不需要輪詢。gRPC services can push messages in real-time without polling.
  • 多語言環境– gRPC 工具支援所有熱門的開發語言,讓 gRPC 成為多語言環境的理想選擇。Polyglot environments – gRPC tooling supports all popular development languages, making gRPC a good choice for multi-language environments.
  • 網路受限的環境– gRPC 訊息會使用 Protobuf (輕量訊息格式)進行序列化。Network constrained environments – gRPC messages are serialized with Protobuf, a lightweight message format. GRPC 訊息一律會小於對等的 JSON 訊息。A gRPC message is always smaller than an equivalent JSON message.

gRPC 弱點gRPC weaknesses

有限的瀏覽器支援Limited browser support

目前無法從瀏覽器直接呼叫 gRPC 服務。It's impossible to directly call a gRPC service from a browser today. gRPC 大量使用 HTTP/2 功能,而且沒有瀏覽器提供 web 要求所需的控制層級來支援 gRPC 用戶端。gRPC heavily uses HTTP/2 features and no browser provides the level of control required over web requests to support a gRPC client. 例如,瀏覽器不允許呼叫端要求使用 HTTP/2,或提供基礎 HTTP/2 框架的存取權。For example, browsers do not allow a caller to require that HTTP/2 be used, or provide access to underlying HTTP/2 frames.

gRPC-Web是 gRPC 團隊提供的額外技術,可在瀏覽器中提供有限的 gRPC 支援。gRPC-Web is an additional technology from the gRPC team that provides limited gRPC support in the browser. gRPC 是由兩個部分組成:支援所有新式瀏覽器的 JavaScript 用戶端,以及伺服器上的 gRPC Web proxy。gRPC-Web consists of two parts: a JavaScript client that supports all modern browsers, and a gRPC-Web proxy on the server. GRPC-Web 用戶端會呼叫 proxy,而 proxy 會在 gRPC 要求上轉送至 gRPC 伺服器。The gRPC-Web client calls the proxy and the proxy will forward on the gRPC requests to the gRPC server.

GRPC-Web 不支援所有 gRPC 的功能。Not all of gRPC's features are supported by gRPC-Web. 用戶端和雙向串流不受支援,而且對伺服器串流的支援有限。Client and bi-directional streaming isn't supported, and there is limited support for server streaming.

不是人類看得懂Not human readable

HTTP API 要求會以文字傳送,並可供人類讀取和建立。HTTP API requests are sent as text and can be read and created by humans.

根據預設,gRPC 訊息會以 Protobuf 編碼。gRPC messages are encoded with Protobuf by default. 雖然 Protobuf 的傳送和接收效率較高,但其二進位格式卻不容易閱讀。While Protobuf is efficient to send and receive, its binary format isn't human readable. Protobuf 需要指定于proto檔案中的訊息介面描述,才能正確還原序列化。Protobuf requires the message's interface description specified in the .proto file to properly deserialize. 需要額外的工具,才能在網路上分析 Protobuf 承載,並以手動方式撰寫要求。Additional tooling is required to analyze Protobuf payloads on the wire and to compose requests by hand.

伺服器反映gRPC 命令列工具等功能都存在,以協助進行二進位 Protobuf 訊息。Features such as server reflection and the gRPC command line tool exist to assist with binary Protobuf messages. 此外,Protobuf 訊息支援JSON 的轉換Also, Protobuf messages support conversion to and from JSON. 內建的 JSON 轉換提供了一種有效率的方式,可在進行偵錯工具時,將 Protobuf 訊息轉換成人類看得懂的格式。The built-in JSON conversion provides an efficient way to convert Protobuf messages to and from human readable form when debugging.

替代架構案例Alternative framework scenarios

在下列案例中,建議您透過 gRPC 使用其他架構:Other frameworks are recommended over gRPC in the following scenarios:

  • 瀏覽器中 – gRPC 的瀏覽器可存取 api不完全受到支援。Browser accessible APIs – gRPC isn't fully supported in the browser. gRPC-Web 可以提供瀏覽器支援,但它有一些限制,而且引進了伺服器 proxy。gRPC-Web can offer browser support, but it has limitations and introduces a server proxy.
  • 廣播即時通訊– gRPC 透過串流支援即時通訊,但將訊息廣播到已註冊連線的概念並不存在。Broadcast real-time communication – gRPC supports real-time communication via streaming, but the concept of broadcasting a message out to registered connections doesn't exist. 例如,在聊天室案例中,新的聊天訊息應傳送至聊天室中的所有用戶端時,每個 gRPC 呼叫都需要個別將新的聊天訊息串流至用戶端。For example in a chat room scenario where new chat messages should be sent to all clients in the chat room, each gRPC call is required to individually stream new chat messages to the client. SignalR在此案例中是有用的架構。SignalR is a useful framework for this scenario. SignalR 具有持續連線的概念,以及廣播訊息的內建支援。 has the concept of persistent connections and built-in support for broadcasting messages.
  • 進程間通訊– 處理常式必須裝載 HTTP/2 伺服器,以接受傳入的 gRPC 呼叫。Inter-process communication – A process must host an HTTP/2 server to accept incoming gRPC calls. 對於 Windows 而言,處理序間通訊管道是快速、輕量的通訊方法。For Windows, inter-process communication pipes is a fast, lightweight method of communication.

其他資源Additional resources