Ocelot网关治理

Ocelot是一个用.NET Core实现并且开源的API网关,它功能强大,包括了:路由、请求聚合、服务发现、认证、鉴权、限流熔断、并内置了负载均衡器与Service Fabric、Butterfly Tracing集成。这些功能只都只需要简单的配置即可完成,下面我们会对这些功能的配置一一进行说明。

1、安装包

Ocelot
Ocelot.Provider.Consul

2、Startup配置

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();


            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "TestGateWay", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseOcelot();
            
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //    app.UseSwagger();
            //    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "TestGateWay v1"));
            //}

            //app.UseHttpsRedirection();

            //app.UseRouting();

            //app.UseAuthorization();

            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapControllers();
            //});
        }
    }

3、Program 配置

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

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(conf =>
            {
                conf.AddJsonFile("configuration.json", optional: false, reloadOnChange: true);
            })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

4、配置文件 configuration.json

//*将用户的请求 /post/1 转发到 localhost/api/post/1*/
/*
      DownstreamPathTemplate:转到的地址
      DownstreamScheme:转到的请求协议
      DownstreamHostAndPorts:转到的端口地址及端口信息
      UpstreamPathTemplate:监听路由地址
      UpstreamHttpMethod:监听路由请求类型 可用数组
      Priority:路由的优先级Prority是大的会被优先选择
      万能模版转发:
 */



//*****************单地址,直连服务**************************
//{
//  "Routes": [
//    {
//      "UpstreamPathTemplate": "/T231/{url}", //网关地址
//      "UpstreamHttpMethod": [ "Get", "Post" ],

//      "DownstreamPathTemplate": "/Api/{url}", //服务地址
//      "DownstreamScheme": "http",
//      "DownstreamHostAndPorts": [
//        {
//          "Host": "localhost",
//          "Port": 6002
//        },
//        {
//          "Host": "localhost",
//          "Port": 6004
//        }
//      ],
//      "LoadBalancerOptions": {
//        "Type": "RoundRobin" //轮流发送
//        // "LeastConnection", 将请求发往最空闲的那个服务器
//        // "NoLoadBalance" – 总是发往第一个请求或者是服务发现
//      }

//    }
//  ]
//}



//***********************Ocelot与Consul ***********************************

{
  "Routes": [
    {
      "UpstreamPathTemplate": "/TaiSu/{url}", //网关地址
      "UpstreamHttpMethod": [ "Get", "Post" ],

      "DownstreamPathTemplate": "/Api/{url}", //服务地址
      "DownstreamScheme": "http",
      "UseServiceDiscovery": true, //使用服务发现
      "ServiceName": "xiaoyaodijun", //Consul 服务名称
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //轮流发送
        // "LeastConnection", 将请求发往最空闲的那个服务器
        // "NoLoadBalance" – 总是发往第一个请求或者是服务发现
      }

    }
  ],
  "GlobalConfiguration": {
    "ServiceDiscoveryProvider": {
      "Host": "127.0.0.1",
      "Port": 8500,
      "Type": "Consul"  //由Consul提供服务,每次请求去Consul
    }
  }
}

 限流

引用包  Ocelot.provider.polly

Startup

           services.AddOcelot().
                          AddConsul().
                          AddPolly().   //限流
                          AddCacheManager(x => {
                              x.WithDictionaryHandle();
                           });
{
  "Routes": [
    {
      "UpstreamPathTemplate": "/TaiSu/{url}", //网关地址
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "DownstreamScheme": "http",
      "DownstreamPathTemplate": "/Api/{url}",
      "UseServiceDiscovery": true, //使用服务发现
      "ServiceName": "xiaoyaodijun", //Consul 服务名称
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //轮流发送
        // "LeastConnection", 将请求发往最空闲的那个服务器
        // "NoLoadBalance" – 总是发往第一个请求或者是服务发现
      },
      "RateLimitOptions": {
      //  "ClientWhiteList": [ "sel" ], 白名单
        "EnableRateLimiting": true, //是否启用限流
        "Period": "5m", //1s 5m 1h 1d
        "PeriodTimespan": 30, //多少秒后客户端可以重试
        "Limit": 5 // 统计时间端内允许的最大请求数
      }

    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://127.0.0.1:7002", //网关对外地址
    "ServiceDiscoveryProvider": {
      "Host": "127.0.0.1",
      "Port": 8500,
      "Type": "Consul" //由Consul提供服务,每次请求去Consul
    }
  },
  "RateLimitOptions": {
    "QuotaExceedeMessage": "too many request later 11s", //当请求过载时提示信息
    "HttpStatusCode": 666, //当请求过载时返回的Code
   // "ClientIdHeader": "Client_id",//用来识别客户端的请求头

  }
}

 

posted @ 2021-08-18 19:05  逍遥帝君  阅读(91)  评论(0编辑  收藏  举报