asp.net core + Ocelot 实现负载均衡、熔断、认证、限流

一、在nuget引用 Ocelot。

二、创建ocelot.json配置文件

  

复制代码
{
  //这里注意,以前是ReRoutes现在是Routes
  "Routes": [
    {
      //Upstream表示上游请求,即客户端请求到API Gateway的请求
      "UpstreamPathTemplate": "/client1/{url}", //请求路径模板
      "UpstreamHttpMethod": [ "Get", "Post" ], //请求方法数组

      //"UseServiceDiscovery": true, //启用服务发现

      //Downstream表示下游请求,即API Gateway转发的目标服务地址
      "DownstreamPathTemplate": "/{url}", //下游请求地址模板
      "DownstreamScheme": "http", //请求协议,目前应该是支持http和https

      //A***************指定单个转发地址
      "DownstreamHostAndPorts": [ //请求服务地址,可以有多个
        {
          "Host": "43.138.199.247",
          "Port": 9000
        }
      ],
    // 限流配置
      "RateLimitOptions": {
        "ClientWhitelist": [], //白名单,不会被限流,为空表示访问的都被限流
        "EnableRateLimiting": true, //是否被开启
        "Period": "1s", //1秒钟超过了Limit定义的会抛异常
        "PeriodTimespan": 1, //超过一秒后才可以重新请求
        "Limit": 1
      },
      "AuthenticationOptions": { //认证
        "AuthenticationProviderKey": "Bearer",
        "AllowedScopes": []
      },

 

//熔断
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3,
"DurationOfBreak": 20,
"TimeoutValue": 5000
}

  • ExceptionsAllowedBeforeBreaking:允许多少个异常请求。
  • DurationOfBreak:熔断的时间(秒)。
  • TimeoutValue:下游请求的处理时间超过多少则将请求设置为超时。
     }

]}
复制代码

Downstream是下游服务配置
UpStream是上游服务配置
Aggregates 服务聚合配置
ServiceName, LoadBalancer, UseServiceDiscovery 配置服务发现
AuthenticationOptions 配置服务认证
RouteClaimsRequirement 配置Claims鉴权
RateLimitOptions为限流配置
FileCacheOptions 缓存配置
QosOptions 服务质量与熔断
DownstreamHeaderTransform头信息转发
DownstreamPathTemplate:下游模板
DownstreamScheme:下游服务http schema
DownstreamHostAndPorts:下游服务的地址,如果使用LoadBalancer的话这里可以填多项
UpstreamPathTemplate: 上游也就是用户输入的请求Url模板
UpstreamHttpMethod: 上游请求http方法,可使用数组

LoadBalancerOptions:
LeastConnection – 将请求发往最空闲的那个服务器
RoundRobin – 轮流发送
NoLoadBalance – 总是发往第一个请求或者是服务发现

 

复制代码
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using System.Net;

var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddRazorPages();
builder.Services.AddOcelot(builder.Configuration);
var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();
app.UseOcelot().Wait();
app.Run();
复制代码

 

posted @   lzy1666  阅读(48)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示