> For the complete documentation index, see [llms.txt](https://chenxing-cao.gitbook.io/space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://chenxing-cao.gitbook.io/space/system-design/rest-vs-rpc.md).

# REST vs RPC

![](/files/-MQskNAcF0FH7nB1Yr5y)

### 1.  什么是 REST? <a href="#id-1-rest" id="id-1-rest"></a>

REST 是 **RE**presentational **S**tate **T**ransfer 的缩写。根据 Roy Fielding, REST 的提出者，REST 有六个核心原则：

* 客户端服务器分离 - 客户端和服务器可以在交互界面 (Interface) 不变的情况下分别迭代
* 无状态 (Stateless) - 客户端向服务器发送的请求包含所有需要处理这个请求的信息，不依赖先前发送的请求。
* 缓存 - 可以选择是否允许对响应 (Response) 进行缓存
* **统一的交互界面 (Uniform Interface) - RESTful API 的界面有统一的标准达到方便交互的目的。具体的标准会在下面的小节着重分析。**
* 系统分层 - 将系统进行层级划分，每一层只能与邻近的层级交互以降低整体系统的复杂度并方便每一层级单独迭代。
* 代码下载 (Code-on-Demand) - 可以选择下载代码并运行。

#### gRPC

A second model for using HTTP for APIs is illustrated by gRPC. gRPC uses HTTP/2 under the covers, but HTTP is not exposed to the API designer. gRPC-generated stubs and skeletons hide HTTP from the client and server too, so nobody has to worry how the RPC concepts are mapped to HTTP—they just have to learn gRPC.&#x20;

The way a client uses a gRPC API is by following these three steps:

1. Decide which procedure to call
2. Calculate the parameter values to use (if any)
3. Use a code-generated stub to make the call, passing the parameter values

#### gRPC是RPC框架

RPC（Remote Procedure Call）—远程过程调用。简单来说，就是我在本地调用了一个函数，或者对象的方法，实际上是调用了远程机器上的函数，或者远程对象的方法，但是这个通信过程对于程序员来说是透明的，即达到了一种位置上的透明性。RPC是一种技术思想而非一种规范。协议只规定了 Client 与 Server 之间的点对点调用流程，包括 stub、通信协议、RPC 消息解析等部分，在实际应用中，还需要考虑服务的高可用、负载均衡等问题<br>

gPRC 的一个很明显的优势是它使用了二进制编码，所以它比 JSON/HTTP 更快。虽然说速度越快越好，但我们也要考虑另外两个因素：清晰的接口规范和对流式传输的支持。<br>
