Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API、WebSockets 和 WebHooks:究竟应该选谁 #8080

Merged
merged 8 commits into from
Mar 10, 2021
82 changes: 41 additions & 41 deletions article/2021/apis-vs-websockets-vs-webhooks-what-to-choose.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,89 +2,89 @@
> * 原文作者:[Chameera Dulanga](https://medium.com/@chameeradulanga)
> * 译文出自:[掘金翻译计划](https://github.com/xitu/gold-miner)
> * 本文永久链接:[https://github.com/xitu/gold-miner/blob/master/article/2021/apis-vs-websockets-vs-webhooks-what-to-choose.md](https://github.com/xitu/gold-miner/blob/master/article/2021/apis-vs-websockets-vs-webhooks-what-to-choose.md)
> * 译者:
> * 译者:[霜羽 Hoarfroster](https://github.com/PassionPenguin)
> * 校对者:
PassionPenguin marked this conversation as resolved.
Show resolved Hide resolved

# APIs vs. WebSockets vs. WebHooks: What to Choose?
# API、WebSockets WebHooks:究竟应该选谁

![](https://cdn-images-1.medium.com/max/5760/1*k3Etz0QztOVwxIMYg1Tatw.jpeg)

If we take any application, we need a reliable mechanism to communicate between its components.
无论开发什么应用,我们都需要一种可靠的机制来进行组件间通信。

For example, in web applications, we need to communicate between browser and server. Sometimes, the server needs to send back messages to the browser. Besides, there are instances where the backend depends on another service that takes a long time to complete.
例如,在 Web 应用中,我们需要在浏览器和服务器之间进行通信;有时,服务器需要将消息返回浏览器;此外,在某些情况下,后端服务还可能依赖于另一个需要很长响应时间的服务。

> **That’s where APIs, WebSockets, and WebHooks come into play. These methods provide a flawless mechanism to communicate and sync data across different parts of an application.**
> **这就是 API、WebSockets WebHooks 发挥作用的地方。它们为该问题提供了完美的解决思路,让我们得以在应用的不同模块之间进行通信和数据同步。

Although these three methods primarily facilitate communication, there are some significant differences between them. So in this article, I will discuss how these three approaches work and how we can choose the most suitable method depending on the use case.
尽管这三种方法主要都是用于通信的,它们之间还是有一些明显的区别。在本文中,我们将讨论如何使用这三种 API,以及如何根据使用场景选择最合适的方法。

## APIs - Provides an interface and a contract for consumers.
## API —— 为用户提供接口和协议。

> **API or Application Programming Interface is a contract between a consumer and the service provider who exposes the API typically over HTTP.**
> **API (应用程序接口)是用户与服务商之间的协议,它通常暴露在 HTTP 请求中。**

This works exceptionally well for scenarios like basic CRUD operations from the web, mobile, or even for service to service integrations. Mostly the communications happen using JSON or XML as the data transfer format.
对于 Web 和移动设备上进行的基本 CRUD 操作,甚至是在集成服务访问别的服务等场景,这个方法都非常有效。大多数情况下,API 通信使用 JSON XML 作为传输数据的格式。

Let’s take a scenario where users search for products on an e-commerce website. Once the user requests what he wants using a search query, he will get a response within few seconds. The process of an API is simple as that.
让我们假设一个场景 —— 用户在电商网站上搜索商品。一旦用户使用搜索查询请求了自己想要查找的商品,他就会在几秒钟内得到响应。API 的工作方式就是如此简单。

![How API Call Works in a Web Application](https://cdn-images-1.medium.com/max/2000/1*2P5Wwur2TEno1WY0lZHP3w.png)
![API 调用在 Web 应用中的工作方式](https://cdn-images-1.medium.com/max/2000/1*2P5Wwur2TEno1WY0lZHP3w.png)

> **As I mentioned initially, API requests are originated from the consumer. So, they are well suited for applications like persisting state or perform a quick action to receive an immediate response from the back-end operation.**
> **正如我最初提到的,API 请求是用户发起的,因此它们非常适合如下应用程序:持久状态、执行快速操作以接收来自后端操作的实时响应。

However, if the server needs to communicate back to the browser, there is no direct method when using APIs unless the browser periodically checks for any updates.
但是,使用 API 的时候,除非浏览器定期发送请求检查更新情况,否则没有一种直接的方法可以让服务器主动与浏览器进行通信。

For example, tasks like report generation could take more time and resources where it is typically done in the background. Therefore once the consumer tells the service provider to generate a report, there is no direct method to notify the completion. The browser might need to poll the API continuously.
举个例子,诸如报告生成之类的任务可能会花费更多的时间和资源,而这通常需要在后台完成。因此用户请求服务商去生成报告后,服务器并没有直接的方法来告知用户任务已完成,我们的浏览器可能需要持续轮询 API

**But polling is not efficient and we have better methods like WebSockets to address such challenges.**
**但是轮询效率不高,我们有更好的方法(如 WebSockets)来解决此类问题。**

## WebSockets - When you need real-time communication
## WebSockets —— 实时通信的一种方案

> **WebSockets, address this challenge by allowing a persistent and bidirectional communication between the consumer and service provider.**
> ** WebSockets 允许用户和服务商之间建立一个持久的双向通信来解决这个问题。

Having a full-duplex communications channel allows service providers to send messages at any time. Since all the modern browsers support WebSockets, it is the best solution for real-time web applications.
使用全双工信道可以让服务器随时向用户发送消息。由于所有现代浏览器都支持 WebSockets,可以说它是实时 Web 应用场景的最佳解决方案。

![How WebSocket Works](https://cdn-images-1.medium.com/max/2690/1*6pyJqsMadK3ItpzWa3qdSA.png)
![WebSockets 的工作方式](https://cdn-images-1.medium.com/max/2690/1*6pyJqsMadK3ItpzWa3qdSA.png)

> **However, keeping the connection open all the time increases resource consumption, power usage (mobile devices), and makes it difficult to scale.**
> **然而一直保持连接打开会消耗资源、影响能耗(移动设备),并且难以扩展服务。**

For example, if we take the same report generation scenario, using WebSockets might be a great option for the web. However, it might not work best for mobile, where we might need to look at technologies like push notifications. Besides, if our backend depends on an external service for generating the report, WebSockets isn’t the best option for the backend to external service communication.
例如,还是考虑上面那个生成报告的场景,在 Web 上使用 WebSockets 可能是一个不错的选择,但对于移动设备来说不是最佳方案,因为我们可能需要研究诸如推送通知之类的技术。此外,如果我们的后端是依赖于外部服务来生成报告的,那么 WebSockets 同样不是后端与外部服务通信的最佳选择。

**That’s where we need a mechanism like WebHooks.**
**WebHooks 这类机制在这里就派上用场了。**

![How to connect consumer, backend, and external services using WebSockets and WebHooks.](https://cdn-images-1.medium.com/max/2006/1*vhbQNBBr2Lmzz2QBa5KYkQ.png)
![如何使用 WebSockets WebHooks 连接用户、后端和外部服务。](Https://cdn-images-1.medium.com/max/2006/1*vhbQNBBr2Lmzz2QBa5KYkQ.png)

## WebHooks - Perfect solution for Backend Callbacks
## WebHooks —— 完美的后端回调解决方案

WebHooks provides a solution for the overkilling issue in WebSockets by providing a disconnected mechanism to receive a response originate from the service provider.
WebHooks 通过提供一种断开机制以接收来自服务商的响应,从而为 WebSockets 中的棘手难题提供了解决方案。

If we look at the technical side, the consumer registers the WebHook (callback URL) into the service provider, and that URL will act as the place to receive data from WebHook.
如果从技术层面来看,用户将 WebHooks(准确来说是回调 URL)注册到服务商中,这个 URL 将充当接收来自 WebHooks 数据的地方。

> **In most cases, this URL belongs to another server, and WebHooks are mostly used to communicate between servers or backend-processes.**
> **在大多数情况下,这个 URL 属于另一台服务器。WebHooks 通常用于在服务器或后端进程之间进行通信。

If we dig deep into the process, we can break this process into four parts.
如果深入研究通信的过程,我们可以将该过程分为四个部分:

![How WebHook Works](https://cdn-images-1.medium.com/max/3000/1*2BYW_05KftDQ4U3XVrXQOA.png)
![WebHooks 的工作方式](https://cdn-images-1.medium.com/max/3000/1*2BYW_05KftDQ4U3XVrXQOA.png)

* **Event Trigger**: This is the event you specified to run the WebHook. Each time the event occurs, WebHook will do its job
* **WebHook provider creates the WebHook and sends POST request:** WebHook provider is responsible for monitoring the event and making the WebHook. Once the event is triggered, the WebHook provider will send the POST HTTP request to the third-party application.
* **The third-party application receives data**: The third-party application will receive data to the URL or the listener you provide to the WebHook provider when registering.
* **The action specified in the third-party application**: Once the application receives the POST request, developers can use the data for anything they want.
* **事件触发器**:这是由你指定的运行 WebHooks 的事件。每当此事件发生时,WebHooks 都会发送请求。
* **WebHooks 提供程序创建 WebHooks 并发送 POST 请求:** WebHooks 提供程序负责监听事件并构建 WebHooks。一旦事件被触发,WebHooks 提供程序会发送一个 HTTP POST 请求发送给第三方应用程序。
* **第三方应用程序接收数据**:第三方应用程序将接收到数据,并转发给 URL 或者我们提供给 WebHooks 提供程序的侦听器。
* **第三方应用程序中指定的操作**:一旦应用程序收到 POST 请求,开发人员就可以任意使用数据。

> **On the surface level, you will feel that it is completely the opposite of the APIs process, and due to that reason, most people refer to WebHooks as Reverse APIs.**
> **从表面上看,大概我们都会觉得这与 API 流程完全相反,因此,大多数人将 WebHooks 称为反向 API。

---

## Conclusion
## 结论

As I have mentioned initially, WebHooks, WebSockets, and APIs facilitate communication; they have various use cases.
正如我最初提到的,WebHooksWebSockets 和 API 都可以用于通信,只是它们具有不同的使用场景。

APIs are the best option for applications where you just need basic CRUD operations and synchronous responses. Also, APIs can be used with both web and mobile applications and service integrations with ease.
对于仅需要基本 CRUD 操作和同步响应的应用程序,API 是最佳选择。而且,API 可以轻松地与 Web 和移动应用程序以及服务集成一起使用。

But, if your web application requires real-time communication with the backend, you should choose WebSockets. It allows you to establish a 2-way communication channel between your browser and the backend.
但是,如果我们的 Web 应用需要与后端进行实时通信,那么我们更应该选择 WebSockets,因为它允许我们在浏览器和后端之间建立双向信道。

However, WebHooks are slightly different from APIs and WebSockets, which is more like a reverse API. Once the Consumer registers the WebHook URL in the service provider, the latter can call the WebHook when required.
但是,WebHooks 与 API 和 WebSockets 稍有不同,它更像是反向 API。一旦用户在服务商处注册了 WebHooks URL,后者就可以在需要时调用 WebHooks。

I think now you understand the different use cases of these communication methods and if you have anything to share, please share in the comments section.
相信现在你已经了解这些通信方式的不同使用场景,如果你有什么想要分享的内容,请在评论区中留言。

Thank you for Reading !!!
感谢你的阅读!

> 如果发现译文存在错误或其他需要改进的地方,欢迎到 [掘金翻译计划](https://github.com/xitu/gold-miner) 对译文进行修改并 PR,也可获得相应奖励积分。文章开头的 **本文永久链接** 即为本文在 GitHub 上的 MarkDown 链接。

Expand Down