首页 > 解决方案 > 调用依赖微服务

问题描述

假设我有 2 个微服务:Service1 和 Service2。他们每个人都有自己的数据库。Service1 有 EntityA,Service2 有 EntityB

EntityA {
    Long id;
    //other fields
    EntityB entity;
}

EntityB{
     //other fields
}

我正在使用 Spring 的 RestTemplate 来检索和保存数据。问题是:当从 Service1 的数据库中检索 EntityA 时,我没有 EntityB 的数据,因为它们保存在 Service2 的数据库中,我知道我应该通过 RestTemplate 进行休息调用以从 Service2 的数据库中检索 EntityB,但是两者之间的关系呢?实体 - EntityA 是否应该仍然在其中包含整个 EntityB 对象,即使它的字段大部分时间都是空的,除了 id ?我错过了什么?先感谢您。

标签: javaspringweb-servicesmicroservices

解决方案


从技术角度来看,您的问题可以通过API Gateway解决。

简而言之,您应该定义一个新的微服务,例如gateway service,将由您的 API 客户端调用。然后gateway service会:

  1. 调用与forService1相处Entity1idEntity2
  2. 调用Service2Entity2根据步骤 1 中的 id 获取。
  3. 聚合两个响应(在你的情况下,设置Entity2里面的值Entity1)。
  4. 将聚合响应返回给客户端。

设计时要记住两件事:

  • 您的 API 客户端不应该知道他的数据是由两个服务获取的。
  • 在网关中聚合客户端响应通常更干净,因为它允许在微服务之间进行更高级别的解耦。例如,您可以按如下方式对您的实体进行建模(并删除 和 之间的数据模型依赖关系Service1Service2从而允许两个服务独立发展)。

请参阅以下代码段:

// In Service1
EntityA {
    Long bId; 
}

// In Service2
EntityB{

}

// In Gateway
Response {
    EntityA a;
    EntityB b;
}

天气Entity1应该参考的决定Entity2不取决于您的数据分布方式,而是取决于您的业务需求。如果您有一个单体应用程序,并且在这种情况下Entity1引用Entity2是有意义的,那么在微服务环境中这样做仍然有意义。


推荐阅读