【问题标题】:Data Aggregation in API Gateway - ZuulAPI 网关中的数据聚合 - Zuul
【发布时间】:2016-12-23 22:21:57
【问题描述】:

我正在寻找一种可以在 API Gateway 中提供某种数据聚合的解决方案。我正在将 spring cloud netflix zuul 用于 API 网关。我使用 Spring Boot 创建了 3 个微服务 -

Catalog - All products 
DeviceInfo - a particular product detail 
Inventory - product stock

这里是 Zuul 配置 -

zuul.routes.deviceInfo.path=/device/deviceInfo/**
zuul.routes.deviceInfo.url=http://localhost:9002/getDeviceInfo

zuul.routes.catalog.path=/device/all/**
zuul.routes.catalog.url=http://localhost:9001/getProductCatalog

zuul.routes.inventory.path=/device/stock/**
zuul.routes.inventory.url=http://localhost:9003/getInventory

ribbon.eureka.enabled=false

server.port=8080

在产品详情页面我需要打两个电话-

http://localhost:8080/device/deviceInfo/ - for product details
http://localhost:8080/device/stock/ - for stock details

有没有办法对 API 网关进行一次调用,将上述两次调用的结果结合起来?两个调用都给出 JSON 作为响应。

【问题讨论】:

  • 但是您为什么要创建单独的服务来单独获得响应。
  • 可能是我对 API 网关的概念有误。那么,打两个电话可以吗?是的,这两项服务都有各自的责任。如果我们必须基于某些业务逻辑聚合两个或多个服务的响应,只需考虑一个场景。那我们该怎么办?或者,这种情况在微服务开发中不应该出现?
  • 我不确定zuul是否真的应该这样做,它主要用于路由。如果可以以任何方式帮助您合并响应,也许您可​​以尝试阅读 zuul 过滤器。但我强烈认为 zuul 不是整合响应的地方。您将服务分开,因为职责不同,并且每个服务都有自己的目的。如果需要将两种响应结合起来,那么最好创建一个新的响应,或者寻找其他解决方案。跨度>
  • 您是否了解如何将它们聚合到一个调用中。 ?

标签: netflix-zuul spring-cloud-netflix


【解决方案1】:

您可以使用聚合器-微服务模式,但不能在 ZUUL 中使用。保持 Zuul 作为无状态网关。 聚合器微服务应该有这样的客户端代码

public String getProductTitle() {
    String response = null;
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
      HttpGet httpGet = new HttpGet("http://localhost:51515/information");
      try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
        response = EntityUtils.toString(httpResponse.getEntity());
      }
    } catch (IOException e) {
      LOGGER.error("Exception caught.", e);
    }
    return response;
  }
}

请看https://github.com/iluwatar/java-design-patterns/tree/master/aggregator-microservices

【讨论】:

    【解决方案2】:

    我认为最初的问题是关于 here 记录的 API 组合模式。 API 组合是微服务生态系统中常用的模式,其中来自客户端的单个调用可能会导致对许多微服务的调用并返回合并的结果。在 API 网关中执行此操作是一种相当普遍的做法,并且还记录在 here

    我自己前段时间用zuul寻找过这个解决方案,但没有找到。也许从那以后情况发生了变化。

    【讨论】:

      猜你喜欢
      • 2020-02-07
      • 2017-08-23
      • 2019-09-12
      • 2021-05-01
      • 2017-07-27
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      • 2020-03-20
      相关资源
      最近更新 更多