且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何合并/整合来自多个 RESTful 微服务的响应?

更新时间:2023-02-15 16:23:45

我们用于此类问题的解决方案是对数据和事件进行非规范化以进行更新.

The solution which we used for such problem was denormalization of data and events for updating.

基本上,一个微服务有一个它需要从其他微服务预先获取的数据子集,这样它就不必在运行时调用它们.这些数据通过事件进行管理.其他微服务在更新时,会触发一个带有 id 作为上下文的事件,任何对其感兴趣的微服务都可以使用该事件.这样数据保持同步(当然它需要某种形式的事件故障机制).这似乎需要做很多工作,但有助于我们做出有关整合来自不同微服务的数据的任何未来决策.我们的微服务将始终拥有本地可用的所有数据,以便处理任何请求而无需同步依赖其他服务

Basically, a microservice has a subset of data it requires from other microservices beforehand so that it doesn't have to call them at run time. This data is managed through events. Other microservices when updated, fire an event with id as a context which can be consumed by any microservice which have any interest in it. This way the data remain in sync (of course it requires some form of failure mechanism for events). This seems lots of work but helps us with any future decisions regarding consolidation of data from different microservices. Our microservice will always have all data available locally for it process any request without synchronous dependency on other services

在您的情况下,即为了显示带有消息的名称,您可以在 Service(B) 中为名称保留一个额外的属性.因此,每当 Service(A) 中的名称更新时,它都会触发一个带有更新名称的 id 的更新事件.然后服务(B) 使用该事件,从服务(A) 获取相关数据并更新其数据库.这样,即使 Service(A) 关闭,Service(B) 也会运行,尽管有一些陈旧的数据,当 Service(A) 出现时这些数据最终会保持一致,并且您将始终在 UI 上显示一些名称.

In your case i.e. for showing names with a message, you can keep an extra property for names in Service(B). So whenever a name update in Service(A) it will fire an update event with id for the updated name. The Service(B) then gets consumes the event, fetches relevant data from Service(A) and updates its database. This way even if Service(A) is down Service(B) will function, albeit with some stale data which will eventually be consistent when Service(A) comes up and you will always have some name to be shown on UI.

https://enterprisecraftsmanship.com/2017/07/05/how-to-request-information-from-multiple-microservices/