Api网关如何组合来自微服务的响应

问题描述 投票:0回答:1

根据https://dzone.com/articles/building-microservices-using条有一条声明:

API网关负责请求路由,组合和协议转换。来自客户端的所有请求都首先通过API网关。然后,它将请求路由到适当的微服务。 API网关通常会通过调用多个微服务并汇总结果来处理请求。

基于Zuul示例,我想知道API网关如何实现这一目标的?

让我们想象一下,我们有两个微服务,一个微服务检索所有可用的产品名称,第二个微服务返回产品的描述。在单片架构中,我们只有一个请求来获取所有需要的数据。在微服务架构中,API网关应组合(来自两个微服务)响应并返回一个响应。

如何实现这种功能?是否有任何准则或文章?

microservices spring-cloud netflix-zuul api-gateway
1个回答
0
投票

并非所有API网关都支持聚合。 This是使用nginx为单个客户端调用聚合两个服务的响应的示例。

这是它的副作用,它在API网关层引入了耦合。

另一个可能的解决方案是使用聚合微服务。该服务的主要职责是提供客户端api。它可以多次调用其他微服务来为客户端制定响应。请参见下面的示例

  @RequestMapping(path = "/product", method = RequestMethod.GET)
  public Product getProduct() {

    var product = new Product();
    String productTitle = informationClient.getProductTitle();
    Integer productInventory = inventoryClient.getProductInventories();

    if (productTitle != null) {
      product.setTitle(productTitle);
    } else {
      product.setTitle("Error: Fetching Product Title Failed"); //Fallback to error message
    }

    if (productInventory != null) {
      product.setProductInventories(productInventory);
    } else {
      product.setProductInventories(-1); //Fallback to default error inventory
    }

    return product;
  }

完整示例here

© www.soinside.com 2019 - 2024. All rights reserved.