调用依赖的微服务

dev*_*oxy 5 java spring web-services microservices

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

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

EntityB{
     //other fields
}
Run Code Online (Sandbox Code Playgroud)

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

小智 2

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

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

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

设计时要记住两件事:

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

请参阅下面的片段:

// In Service1
EntityA {
    Long bId; 
}

// In Service2
EntityB{

}

// In Gateway
Response {
    EntityA a;
    EntityB b;
}
Run Code Online (Sandbox Code Playgroud)

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