记录一下接口限流中间件AspNetCoreRateLimit的基本用法
首先添加nuget包AspNetCoreRateLimit
在Program里面注入配置项
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<IpRateLimitOptions>(builder.Configuration.GetSection("IpRateLimiting"));
builder.Services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
builder.Services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();
builder.Services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
var app = builder.Build();
app.UseIpRateLimiting();
在配置文件appsetting.json中添加配置项
"IpRateLimiting": {
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": false,
"RealIPHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"QuotaExceededResponse": {
"Content": "{{"Code":429,"Message":"访问过于频繁,请稍后重试","Data":false}}",
"ContentType": "application/json",
"StatusCode": 429
},
"HttpStatusCode": 429,
"GeneralRules": [
{
"Endpoint": "*:/api/v1/*",
"Period": "1s",
"Limit": 2
},
{
"Endpoint": "*:/api/v2/*",
"Period": "2s",
"Limit": 3
},
{
"Endpoint": "*",
"Period": "1m",
"Limit": 30
}
]
}
大致说明一下以上规则所代表的意思
Endpoint:端点匹配模式,*表示所有
Period:限制周期,1s为1秒,还有1m、1h、1d等
Limit:限制次数,直接填数字即可
*:/api/v1/* 其中第一个*代表请求方式,可以填写get、post特定的请求方式,*代表包含所有请求方式,
/api/v1/*代表请求地址为/api/v1/下的所有请求,例如/api/v1/admin,/api/v1/user
各字段的详细说明可以参考官方文档
当你请求过于频繁就会触发限流,接口统一返回appsetting所定义的content
并且控制台会输出提示信息
[2024-04-24 17:52:17]info: AspNetCoreRateLimit.IpRateLimitMiddleware[0]
Request get:/api/v1/student from IP ::1 has been blocked, quota 2/1s exceeded by 1.
Blocked by rule *:/api/v1/*, TraceIdentifier 0HN348GJK60C9:0000000A. MonitorMode: False
这里触发了第一个规则,访问了api/v1/下的student接口,访问量超过了每秒2次,所以被限流了
除此之外还有针对IP限流和客户端ID限流的配置,后续有时间的话再补充