如何使用Websocket更新REST API请求状态 [英] How to update REST API request status with Websockets

查看:160
本文介绍了如何使用Websocket更新REST API请求状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是基于REST API的内部AngularJS SPA,问题是某些REST请求会持续很长时间(〜5-10秒).

I work with internal AngularJS SPA, based on REST API and problem is some REST requests proceeds for very a long time (~5-10 seconds).

这是可笑的,但与它无关.服务器需要从不同来源获取大量数据,然后对它们进行数学运算,然后做出响应.

It is ridiciolus, but there is nothing to do with it – server need to get a lot of data from different sources and math it together before response.

好的解决方案是向用户显示请求状态,这里我们介绍WebSockets.

Nice solution is to show request status to user, and here we come to the WebSockets.

向用户显示请求状态的示例

Example of request status showing to user

  1. 请求已发送
  2. 请求已接受
  3. 从DB1获取数据
  4. 从DB2获取数据
  5. 数学数据
  6. 准备响应

但是有很多问题.

尚不清楚如何获取哪个API用户发送请求以通知其状态.可能的解决方案是使用字典"API客户端"-"Websocket连接",但是每次重新连接时它都会崩溃,并导致内存泄漏.不是吗?

It is unclear how to get which API user send an request to notify its status. Possible solution is to have dictionary "API client"-"Websocket connection", but it can blows up on every reconnection and cause memory leaks. Isn`t it?

也许解决方案是将整个REST API更改为Websockets.但这似乎需要很多工作,但我仍然需要重新发明诸如缓存之类的东西.

Maybe solution is to change whole REST API to Websockets. But it looks like a lot of work here and still I`ll need to reinvent thing like caching.

从任何角度看,它看起来都是一团糟.什么是更好的解决方案?

It looks like a mess from any angle. What is the better solution here?

推荐答案

最好同时提供REST和Websocket,因此网页可以使用不带websocket支持的websocket和自动客户端,并且仍然使用API​​. 您可以异步处理这些请求,并使用 REST异步模式.

It is better to provide both things, REST and Websocket, so web pages can use the websocket and automated clients with no websocket support and still use the API. You can process those request asynchronously, and use the REST async pattern.

  1. 客户端向API发送请求.
  2. API获取请求并:
    • 为此处理任务创建唯一的ID.
    • 将该任务的详细信息记录在数据存储中.
    • 将消息发送到消息总线,以请求具有该ID的任务进行处理.
    • 使用Location标头将HTTP 202 Accepted返回到提供任务状态的队列端点/queue/<taskid>.
  1. Client sends request to API.
  2. API gets the request and:
    • Creates an unique id for this processing task.
    • Records the details of this task in a data store.
    • Sends a message to a message bus requesting the task with that id to be processed.
    • Returns HTTP 202 Accepted with a Location header to a queue endpoint /queue/<taskid> that provides the status of the task.
  • 转到数据存储以获取该任务ID的详细信息.
  • 进行处理.
  • 完成后,使用该ID更新任务的状态.

Websocket:

  1. 在会话开始时建立了一个websocket连接.
  2. websocket服务器将传入的消息转换为消息总线中的订阅操作,并将订阅消息转换为websocket中的消息.例子:
  1. A websocket connection is established at the beginning of the session.
  2. The websocket server translates the incoming messages to subscribe operations in the message bus, and subscription messages to messages in the websocket. Examples:
    • If you are using Redis.
    • If you are using RabbitMQ.

这篇关于如何使用Websocket更新REST API请求状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆