【问题标题】:How Api gateway combine responses form microservicesApi 网关如何将响应组合成微服务
【发布时间】:2020-02-29 05:13:36
【问题描述】:

https://dzone.com/articles/building-microservices-using文章有说法:

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

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

假设我们有 2 个微服务,一个用于检索所有可用的产品名称,另一个用于返回产品描述。在单体架构中,我们只有一个请求来获取所有需要的数据。在微服务架构中,API 网关应该组合响应(来自两个微服务)并返回一个响应。

这个功能应该如何实现?有没有这方面的指南或文章?

【问题讨论】:

    标签: microservices spring-cloud netflix-zuul api-gateway


    【解决方案1】:

    并非所有 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

    【讨论】:

    • 但是在聚合模式的情况下,我们失去了 API 网关的主要目的,我们基本上用另一个面向客户的微服务来替代 API 网关。是有效的做法吗?
    猜你喜欢
    • 2019-09-12
    • 2019-02-08
    • 2016-04-10
    • 2019-04-06
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2021-05-18
    相关资源
    最近更新 更多