Api网关如何组合响应以形成微服务

时间:2019-11-03 19:57:26

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

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

  

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

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

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

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

1 个答案:

答案 0 :(得分: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