java - 调用依赖微服务
问题描述
假设我有 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 ?我错过了什么?先感谢您。
解决方案
从技术角度来看,您的问题可以通过API Gateway解决。
简而言之,您应该定义一个新的微服务,例如gateway service
,将由您的 API 客户端调用。然后gateway service
会:
- 调用与for
Service1
相处Entity1
id
Entity2
- 调用
Service2
以Entity2
根据步骤 1 中的 id 获取。 - 聚合两个响应(在你的情况下,设置
Entity2
里面的值Entity1
)。 - 将聚合响应返回给客户端。
设计时要记住两件事:
- 您的 API 客户端不应该知道他的数据是由两个服务获取的。
- 在网关中聚合客户端响应通常更干净,因为它允许在微服务之间进行更高级别的解耦。例如,您可以按如下方式对您的实体进行建模(并删除 和 之间的数据模型依赖关系
Service1
,Service2
从而允许两个服务独立发展)。
请参阅以下代码段:
// In Service1
EntityA {
Long bId;
}
// In Service2
EntityB{
}
// In Gateway
Response {
EntityA a;
EntityB b;
}
天气Entity1
应该参考的决定Entity2
不取决于您的数据分布方式,而是取决于您的业务需求。如果您有一个单体应用程序,并且在这种情况下Entity1
引用Entity2
是有意义的,那么在微服务环境中这样做仍然有意义。
推荐阅读
- regex - 模式内的 Grep 模式
- php - 显示 Jquery Ajax 结果的问题
- python-3.x - 无法在 Windows 10 中安装 Pymongo
- arrays - MATLAB - 制作一组四元数数据
- android - 在android中启动应用程序后显示锁定屏幕
- android - 如何在 AndroidStudio xml-preview 中启用布局装饰(例如操作栏)?
- flutter - 使用循环进度指示器时底部溢出
- c# - 访问 Azure 密钥保管库时出现间歇性错误 - 密钥集不存在
- mysql - 如何在sql查询中使用动态限制
- sapui5 - 防止 sap.m.popover 在点击时关闭