.NET Core 微服务 - API 网关之 Ocelot 请求聚合、多个配置

作者:vkvi 来源:ITPOW(原创) 日期:2022-3-31

请求聚合

接上篇文章,我们访问了天气服务,现在我们又增加了一个城市服务

这就有了 2 个服务,访问 2 个服务,再将数据对应起来,就知道哪个城市是怎样的天气了。

这意味着要发起 2 个请求,能不能使用 1 个请求呢?

能,这就是使用聚合了!

只需要修改 ocelet.json 文件。

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/city",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 7107
        }
      ],
      "UpstreamPathTemplate": "/cs",
      "UpstreamHttpMethod": [ "Get" ],
      "Key": "City"
    },
    {
      "DownstreamPathTemplate": "/weatherforecast",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 7219
        }
      ],
      "UpstreamPathTemplate": "/tq",
      "UpstreamHttpMethod": [ "Get" ],
      "Key": "Weather"
    }
  ],
  "Aggregates": [
    {
      "RouteKeys": [
        "City",
        "Weather"
      ],
      "UpstreamPathTemplate": "/"
    }
  ]
}

注意:

  • 两个路由,配置了不同的 Key

  • 两个路由的 UpstreamPathTemplate 不得相同,毕竟除了聚合访问,还是要允许人家单独访问嘛。

  • 配置 Aggregates,注意 RouteKeys,哪个 Key 在前,返回的结果中,就是哪个数据在前。

结果如下

Ocelot 聚合

注意:聚合只能使用 GET 谓词。

多个配置

可以把所有路由写在一个配置文件中,但是路由一多,管理麻烦,所以可以写成多个。

文件名规则:(?i)ocelot.([a-zA-Z0-9]*).json

比如:ocelot.1.json、ocelot.2.json、ocelot.3.json

建立好了之后,Visual Studio 会自动生成一个 ocelot.json 来管理整个配置文件,如下:

多个配置文件

这就可以了。

官方说要将 .AddJsonFile("ocelot.json") 这句改成 .AddOcelot(hostingContext.HostingEnvironment),其实用不着啊,因为我们 Visual Studio 已经自动帮我们处理好了 ocelot.json。当然,你改了,程序也不会报错。

题外

如果咱们的 json 配置有问题(包括 URL 冲突这些),启动时会报错“没有与此对象关联的进程”,所以看到这个错误,有可能是我们程序写错了,还有可能是我们配置有问题噢。

相关文章