.Net Core Ocelot网关使用熔断、限流 二

先安装Ocelot.Provider.Polly

 

 然后在Startup.CS    .AddPolly();

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using Ocelot.Provider.Polly;

namespace WebOclot
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot().AddConsul().AddPolly();
            // 删除掉此处所有默认的配置

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseOcelot();
            // 删除掉此处所有默认的配置
        }
    }
}

Ocelot Json文件配置

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/{url}", // 服务地址--URL变量             **********webapi中 配置 "/api/{url}"  ******************
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/sopweb/{url}", // 网关地址--url变量        ***********webapi中 配置  "/api/{url}"   *************不要sopweb
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "UseServiceDiscovery": true,
      "ServiceName": "sopweb", // consul 服务名称
      "LoadBalancerOptions": {
        "Type": "RoundRobin" // 轮询 方式   LeastConnection  最少的连接数服务器   NoLoadBalance  不负载均衡
      },  //  下面是配置熔断
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3, // 允许失败的异常次数
        "DurationOfBreak": 10000, //熔断的时间,单位为ms
        "TimeoutValue": 4000   //  如果下游的处理时间超过4S则视为请求异常,不时不设置黑认为90s
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:1140",   // 网关对外地址
    "ServiceDiscoveryProvider": {
      "Host": "47.92.27.244",   // 微服务主节点地址
      "Port": 8500,             // 微服务主节点端口号  
      "Type": "Consul"          // 由Consul提供服务发现,每次请求Consul
    }
  }

}

Program.cs  加载配置json

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace WebOclot
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(conf=> {
                conf.AddJsonFile("OcelotSetting.json", optional: false,
                   reloadOnChange: true);
            })
                .UseStartup<Startup>();
    }
}

 限流配置

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/{url}", // 服务地址--URL变量
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/sopweb/{url}", // 网关地址--url变量
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "UseServiceDiscovery": true,
      "ServiceName": "sopweb", // consul 服务名称
      "LoadBalancerOptions": {
        "Type": "RoundRobin" // 轮询 方式   LeastConnection  最少的连接数服务器   NoLoadBalance  不负载均衡
      },  // 下面节点为限流配置代码
      "RateLimitOptions": {
        "ClientWhitelist": [ "eleven", "seven" ], // 白名单 ClientId 区分大小写  白名单请求不受限制
        "EnableRateLimiting": true,   // 是否启用限流
        "Period": "5m", // 1s 5m 1h 1d  单位时间
        "PeriodTimespan": 30, // 多少秒之后客户端可以重试
        "Limit": 5   // 时间段内允许最大请求的数量

      },  //  下面节点是配置熔断
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3, // 允许失败的异常次数
        "DurationOfBreak": 10000, //熔断的时间,单位为ms
        "TimeoutValue": 4000   //  如果下游的处理时间超过4S则视为请求异常,不时不设置黑认为90s
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:1140",   // 网关对外地址
    "ServiceDiscoveryProvider": {
      "Host": "47.92.27.244", // 微服务主节点地址
      "Port": 8500, // 微服务主节点端口号  
      "Type": "Consul" // 由Consul提供服务发现,每次请求Consul
    },
    "RateLimitOptions": {   // 配置限流返回数据状态码  写不写无所谓
      "QuotaExceededMessage": "服务器太繁忙……,请30s后面试……",
      "HttpStatusCode": 666
    }

  }

}

 关于限流白名单说明: 在请求时指定ClientId参数即可,见下图

 

posted @ 2020-08-22 11:43  酒沉吟  阅读(473)  评论(0编辑  收藏  举报