问题描述
我们正在构建一个微服务应用程序,客户可以在其中创建项目。下图显示了此过程的技术流程:
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,但问题是我还不知道位置
( / projects / {id}
),因为项目的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.
推荐答案
考虑到在请求时不知道新创建的项目
实体的ID(即它是在插入数据库之后生成的),您确实无法生成到项目
资源。
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
)到c在发送到总线并在API网关本身上跟踪其执行状态之前的ommand。然后,您可以使用命令执行状态端点响应客户端,例如 / 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).
第三种解决方案可能是使用项目
surogate ID,如GUID,被指定为项目的属性
,包含在命令中,具有可以仅在进程的预创建阶段使用的备用标识的目的。然后,对客户端的响应可能是这样的: / projects / by-guid / 1234-abcd-5678-efgh
并且在项目之后
创建 GET
到此 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响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!