微服务异步操作 HTTP 响应 [英] Microservices async operation HTTP response

查看:24
本文介绍了微服务异步操作 HTTP 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在构建一个微服务应用,客户可以在其中创建项目.下图展示了这个过程的技术流程:

We're building a microservice app where clients can create projects. The following diagram shows the technical flow of this process:

我的问题:API 网关应该向客户端返回什么 HTTP 响应(第 1 步)?

我最初的想法是返回 202,但问题是我还不知道 Location (/projects/{id}),因为 project 的 id 将在项目管理服务中创建.

My initial idea was to give back a 202, but the problem there is that I don't know the Location yet (/projects/{id}), because the id of the project will be created at the Project Management Service.

推荐答案

考虑到新创建的 project 实体的 ID 在请求时是未知的(即它是在插入到数据库)您确实无法生成 project 资源的 url.

Considering that the IDs of the newly created project entity is not known at the request time (i.e. it is generated after the insertion into the database) you indeed cannot generate the url to the project resource.

相反,您可以在发送到总线之前为命令分配一个 ID(即 1234-abcd-5678-efgh),并在 API 网关本身上跟踪其执行状态.然后,您可以使用命令执行状态端点(如 /commands/1234-abcd-5678-efgh)响应客户端,它可以通过轮询进行查询.

Instead, you could assign an ID (i.e. 1234-abcd-5678-efgh) to the command before sending to the bus and keep track of its execution status on the API gateway itself. Then you can respond to the client with an command execution status endpoint like /commands/1234-abcd-5678-efgh where it can query by polling.

另一种方法是使用另一个可以保留和提供唯一 ID 的服务,但您必须对其进行阻塞调用,这会损害可扩展性.或者,您可以在 API 网关内部(在同一节点上)托管此服务以最大程度地减少延迟.此外,在项目创建失败的情况下,存在丢失某些 ID 的风险,但可以通过在这些情况下释放这些 ID 来弥补这一点(从而增加架构复杂性).

The alternative would be to use another service that would reserve&deliver unique IDs but you must make a blocking call to it and this hurts scalability. Or you can host this service inside the API gateway itself (onto the same node) to minimize latency. Also, there is a risk of loosing some IDs in case of project creation failures but this can be compensated by releasing those IDs in those situations (thus increasing the architecture complexity).

第三种解决方案可能是使用 project 代理 ID,如 GUID,作为 project 的属性分配,包含在命令中,具有目的只能在流程的预创建阶段使用的替代身份.然后,对客户端的响应可能是这样的:/projects/by-guid/1234-abcd-5678-efgh 并且在创建 project 之后,一个 GET 到这个 url 将永久重定向到最终的项目 url.

A third solution could be the use of a project surogate ID, like a GUID, assigned as a property of the project, included in the command, having the purpose of an alternate identity that can be used only in the pre-creation phase of the process. Then, the response to the client could be like this: /projects/by-guid/1234-abcd-5678-efgh and after the project is created a GET to this url would permanently redirect to the final project url.

这篇关于微服务异步操作 HTTP 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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