zoukankan      html  css  js  c++  java
  • 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",//用来识别客户端的请求头
    
      }
    }
  • 相关阅读:
    CEO良言:创业就请在29岁前做富翁
    在酒桌上看出她是哪种女人!
    巴菲特的人生财富课
    曹操的领导力:羊群变狮群(领导艺术终极体现)
    商业模式木桶短板原理与长板原理
    这三种力量,让你的人生从此大不一样……
    都市男女的30句妙语叹息
    郎咸平:诸葛亮是一名优秀的企业家吗?
    做小生意,解决生活中的问题:创业路上的成功感悟
    100个成功经验(价格不菲的培训课程笔记摘要)
  • 原文地址:https://www.cnblogs.com/xiaoyaodijun/p/15158396.html
Copyright © 2011-2022 走看看