比较 gRPC 服务和 HTTP APICompare gRPC services with HTTP APIs

作者:James Newton-KingBy James Newton-King

本文介绍如何将 gRPC 服务与具有 JSON 的 HTTP API(包括 ASP.NET Core Web API)进行比较。This article explains how gRPC services compare to HTTP APIs with JSON (including ASP.NET Core web APIs). 用于为应用提供 API 的技术是一个重要选择,与 HTTP API 相比,gRPC 提供独特优势。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 和具有 JSON 的 HTTP API 之间的功能进行了简单比较。The following table offers a high-level comparison of features between gRPC and HTTP APIs with JSON.

功能Feature gRPCgRPC 具有 JSON 的 HTTP APIHTTP APIs with JSON
协定Contract 必需 ( .proto)Required (.proto) 可选 (OpenAPI)Optional (OpenAPI)
协议Protocol HTTP/2HTTP/2 HTTPHTTP
PayloadPayload Protobuf(小型,二进制)Protobuf (small, binary) JSON(大型,人工可读取)JSON (large, human readable)
规定性Prescriptiveness 严格规范Strict specification 宽松。Loose. 任何 HTTP 均有效。Any HTTP is valid.
流式处理Streaming 客户端、服务器,双向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 的主要版本)而设计,与 HTTP 1.x 相比,HTTP/2 具有巨大性能优势: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.

HTTP/2 不是 gRPC 独占的。HTTP/2 is not exclusive to gRPC. 许多请求类型(包括使用 JSON 的 HTTP API)都可以使用 HTTP/2,并受益于其性能改进。Many request types, including HTTP APIs with JSON, can use HTTP/2 and benefit from its performance improvements.

代码生成Code generation

所有 gRPC 框架都为代码生成提供一流支持。All gRPC frameworks provide first-class support for code generation. .proto 文件是 gRPC 开发的核心文件,它定义 gRPC 服务和消息的协定。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.

流式处理Streaming

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-Web 由两部分组成:支持所有现代浏览器的 JavaScript 客户端,以及服务器上的 gRPC-Web 代理。gRPC-Web consists of two parts: a JavaScript client that supports all modern browsers, and a gRPC-Web proxy on the server. gRPC-Web 客户端调用代理,代理将根据 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.

提示

.NET Core 对 gRPC-Web 提供支持。.NET Core has support for gRPC-Web. 有关详细信息,请访问 在浏览器应用中使用 gRPCVisit 在浏览器应用中使用 gRPC for more information.

非人工可读取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:

  • 浏览器可访问的 API:gRPC 在浏览器中未受到完全支持。Browser accessible APIs: gRPC isn't fully supported in the browser. gRPC-Web 可以提供浏览器支持,但它具有局限性并引入了服务器代理。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