netcore自定义中间件实现限流
netcore限流
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
public class RateLimitMiddleware
{
private readonly RequestDelegate _next;
private readonly IMemoryCache _cache;
private readonly int _limit;
private readonly TimeSpan _interval;
public RateLimitMiddleware(RequestDelegate next, IMemoryCache cache, int limit, TimeSpan interval)
{
_next = next;
_cache = cache;
_limit = limit;
_interval = interval;
}
public async Task InvokeAsync(HttpContext context)
{
var cacheKey = GetCacheKey(context.Request.Path);
var requestCount = _cache.GetOrCreate(cacheKey, entry =>
{
entry.SetSlidingExpiration(_interval);
return 0;
});
if (requestCount >= _limit)
{
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
await context.Response.WriteAsync($"Rate limit exceeded. Try again in {_interval.TotalSeconds} seconds.");
}
else
{
_cache.Set(cacheKey, requestCount + 1, _interval);
await _next(context);
}
}
private string GetCacheKey(string path)
{
return $"ratelimit:{path}";
}
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<RateLimitMiddleware>(limit: 100, interval: TimeSpan.FromMinutes(1));
// ...
}
这个示例中,将 RateLimitMiddleware 注册为全局 Middleware,并指定最大请求数为 100,限制时间为 1 分钟。
使用 Middleware 实现接口限流可以灵活地控制请求的流量,提高服务的可靠性和稳定性。同时,也可以通过配置不同的参数来适应不同的业务需求。
2025-05-09 16:13:40【出处】:https://www.cnblogs.com/wwwan/p/17223287.html
=======================================================================================
关注我】。(●'◡'●)
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的【因为,我的写作热情也离不开您的肯定与支持,感谢您的阅读,我是【Jack_孟】!
本文来自博客园,作者:jack_Meng,转载请注明原文链接:https://www.cnblogs.com/mq0036/p/18868390
【免责声明】本文来自源于网络,如涉及版权或侵权问题,请及时联系我们,我们将第一时间删除或更改!