Skip to content
L edited this page Jun 4, 2021 · 5 revisions

概念

上游:服务消费方(eg.MVC Server, SPA App)的调用配置,进来的请求
下游:提供API服务的配置,跳转的实际请求地址

配置说明

{
  "ReRoutes": [
    {
      //Upstream表示上游请求,即客户端请求到API Gateway的请求
      "UpstreamPathTemplate": "/Service1/{url}", //请求路径模板
      "UpstreamHttpMethod": [ "Get", "Post" ], //请求方法数组
 
      "UseServiceDiscovery": false, //启用服务发现
 
      //Downstream表示下游请求,即API Gateway转发的目标服务地址
      "DownstreamPathTemplate": "/api/{url}", //下游请求地址模板
      "DownstreamScheme": "http", //请求协议,目前应该是支持http和https
      //A***************指定单个转发地址
      "DownstreamHostAndPorts": [ //请求服务地址
        {
          "Host": "localhost",
          "Port": 7001
        }
      ]
    }
  ]
}

UpstreamPathTemplate:上游
DownstreamPathTemplate:下游
DownstreamHostAndPorts:下游服务地址
UpstreamHttpMethod:允许的请求方法(GET、POST、PUT、DELETE)

Ocelot+Consul

配置添加:

 "GlobalConfiguration": {
    //"BaseUrl": "https://api.mybusiness.com"
    "ServiceDiscoveryProvider": {
      "Host": "192.168.80.100", // Consul Service IP
      "Port": 8500  // Consul Service Port
    }
  }

BaseUrl:Ocelot外部暴露的Url
ServiceDiscoveryProvider:Consul的IP和端口号
同时去掉ReRoutes节点里面单独配置的DownstreamHostAndPorts

Ocelot支持功能

负载均衡

{
  "ReRoutes": [
      ......
      "LoadBalancerOptions": {
        "Type": "RoundRobin"
      },
      ......  
}

负载均衡LoadBalance可选值:

RoundRobin - 轮询,挨着来,雨露均沾
LeastConnection - 最小连接数,谁的任务最少谁来接客
NoLoadBalance - 不要负载均衡,让我一个人累死吧 

请求缓存

对下游服务的URL进行缓存,并可以设置一个以秒为单位的TTL使缓存过期
缓存期内不会再访问下游服务,而是直接返回结果

限流

对请求进行限流可以防止下游服务器因为访问过载而崩溃

熔断器(QoS)

停止将请求转发到下游服务。当下游服务已经出现故障的时候再请求也是无功而返,并且还会增加下游服务器和API网关的负担。这个功能是用的Pollly来实现的

动态路由(Dynamic Routing)

参考资料

Ocelot的使用(基本使用)
.NET Core微服务之基于Ocelot实现API网关服务
.NET Core微服务之基于Ocelot实现API网关服务(续)
.NET Core开源API网关 – Ocelot中文文档
ocelot官方文档

Clone this wiki locally