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();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步