ASP.NET Core 的 Web Api 实现限流 中间件

在ASP.NET Core中实现Web API限流的一个常见方法是使用中间件来限制并发请求的数量。以下是一个简单的中间件示例,用于限制API端点的并发访问量:




using Microsoft.AspNetCore.Http;
using System.Collections.Concurrent;
using System.Threading.Tasks;
 
public class ConcurrencyLimiterMiddleware
{
    private static readonly ConcurrentDictionary<string, int> _requests = new ConcurrentDictionary<string, int>();
    private readonly RequestDelegate _next;
    private readonly int _maxConcurrentRequests;
 
    public ConcurrencyLimiterMiddleware(RequestDelegate next, int maxConcurrentRequests)
    {
        _next = next;
        _maxConcurrentRequests = maxConcurrentRequests;
    }
 
    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Path.StartsWithSegments("/api/"))
        {
            await _next(context);
            return;
        }
 
        var key = context.Request.HttpContext.Connection.RemoteIpAddress.ToString();
        int count;
 
        while (true)
        {
            // 尝试添加或更新key的计数
            if (_requests.TryAdd(key, 1) || _requests.TryUpdate(key, 1, 0))
            {
                // 成功添加或更新,继续处理请求
                count = _requests[key];
                break;
            }
            // 如果key已经在字典中,尝试更新其计数
            else if (_requests.TryGetValue(key, out count) && count < _maxConcurrentRequests)
            {
                // 更新成功,继续处理请求
                _requests[key] = count + 1;
                break;
            }
            // 如果已达到最大并发请求限制,则等待一段时间后重试
            await Task.Delay(100);
        }
 
        try
        {
            await _next(context);
        }
        finally
        {
            // 请求处理完毕后,将计数器减一
            _requests[key] = count - 1;
        }
    }
}
 
// 在Startup.cs中配置服务和中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...
 
    // 添加并发请求限制中间件
    app.UseMiddleware<ConcurrencyLimiterMiddleware>(10); // 最多允许10个并发请求
 
    // ...
}

这个中间件ConcurrencyLimiterMiddleware会根据远程IP地址对每个请求进行计数,并且如果并发请求数量超过了设定的阈值,它会等待并重试。这个简单的实现没有考虑清理过期的IP地址记录或者更复杂的限流策略,但它展示了如何使用中间件来实现基本的限流功能。

评论已关闭

推荐阅读

Vue中使用mind-map实现在线思维导图
2024年08月04日
VUE
Web前端最全Vue实现免密登录跳转的方式_vue怎么样不登录返回首页,最强技术实现
2024年08月04日
VUE
vue3 项目搭建教程(基于create-vue,vite,Vite + Vue)
2024年08月04日
VUE
Vue-颜色选择器实现方案——>Vue-Color( 实战*1+ Demo*7)
2024年08月04日
VUE
Vue项目卡顿慢加载?这些优化技巧告诉你!_vue数据多渲染卡顿
2024年08月04日
VUE
vue中的keep-alive详解与应用场景
2024年08月04日
VUE
Vue、React实现excel导出功能(三种实现方式保姆级讲解)
2024年08月04日
vue-office/docx插件实现docx文件预览
2024年08月04日
VUE
java调用js文件的两种方法(支持V8引擎)
2024年08月04日
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2024年08月04日
两周从爬虫小白变大神 _yjs_js_security_passport
2024年08月04日
JS笔记(对象、函数、数组)
2024年08月04日
Markdown.js:强大的纯JavaScript Markdown解析器
2024年08月04日
Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
2024年08月04日
vue 父组件怎么获取子组件里面的data数据
2024年08月04日
VUE
个人开发实现AI套壳网站快速搭建(Vue+elementUI+SpringBoot)
2024年08月04日
el-table 表格封装并改造实现单元格可编辑
2024年08月04日
none
nodejs环境下创建vue项目、SSH密钥登陆!!!
2024年08月04日
vue+quill+element-ui实现视频、图片上传及缩放保姆级教程,轻松使用富文本
2024年08月04日
【three.js】22. Imported Models导入模型
2024年08月04日