当前位置:网站首页>net6的Web MVC项目实现限流功能
net6的Web MVC项目实现限流功能
2022-08-11 05:24:00 【Three Big Stones】
原理:利用MemoryCache服务组件,记录用户最后一次访问接口的时间,如果本次访问距离最后一次访问不超过1秒,提示用户访问过于频繁,否则,接口可以正常访问。然后利用拦截器可以拦截action的能力,自定义自己的限流器,结合MemoryCache组件,可以达到简单限流的目的。
1、实现限流器,主要是实现IAsyncActionFilter接口,给构造器注入缓存服务,并实现OnActionExecutionAsync方法,结合缓存功能,记录用户的ip信息作为key值,访问时间作为value。
public class RateLimitFilter : IAsyncActionFilter
{
private IMemoryCache memoryCache;
public RateLimitFilter(IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
}
public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
string remoteIP = context.HttpContext.Connection.RemoteIpAddress.ToString();
string cacheKey = $"LastVisitTick_{remoteIP}";
long? lastTick = memoryCache.Get<long?>(cacheKey);
if (lastTick == null || Environment.TickCount64 - lastTick > 1000)
{
memoryCache.Set(cacheKey, Environment.TickCount64, TimeSpan.FromSeconds(10));//距离现在10秒过期
return next();
}
else//1秒之内只允许访问一次
{
context.Result = new ContentResult{ StatusCode = 429, Content="你访问太频繁了" };
return Task.CompletedTask;
}
}
}2、注册限流器,实现了限流器之后,我们要把它注入到IOC容器中,具体代码如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvcCore(opt => {
opt.Filters.Add<RateLimitFilter>();//添加限流支持
opt.Filters.Add<TransactionScopeFilter>();//添加事务支持
opt.Filters.Add<ExceptionFilter>();//添加异常处理支持
opt.Filters.Add<LogFilter>();
});
services.AddDbContext<BookDbContext>(opt=> {
var connectString = this.Configuration.GetSection("DbConnectionStr").Value;
opt.UseSqlServer(connectString);
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication1", Version = "v1" });
});
services.AddMemoryCache();//添加缓存服务
}3、这样限流的功能算是启用了。
边栏推荐
- AI智能图像识别的工作原理及行业应用
- Zhejiang University School of Software 2020 Guarantee Research Computer Real Question Practice
- CVPR2020:Seeing Through Fog Without Seeing Fog
- Maykle Studio - Second Training in HarmonyOS App Development
- 梅科尔工作室-HarmonyOS应用开发第三次培训
- yolov3+centerloss+replay buffer实现单人物跟踪
- 需求文档(PRD)撰写指南
- The selection points you need to know about the helmet identification system
- 第七届集美大学程序设计竞赛(个人赛)题解
- Hard hat recognition algorithm
猜你喜欢

用正则验证文件名是否合法

基于AI智能图像识别:4个不同的行业应用

AIDL 简介以及使用

跨应用间调用: URL Scheme

Joint 3D Instance Segmentation and Object Detection for Autonomous Driving

The latest safety helmet wearing recognition system in 2022

Safety helmet identification system - escort for safe production

The working principle and industry application of AI intelligent image recognition

SWOT分析法

【调试记录1】提高MC3172浮点运算能力,IQmath库的获取与导入使用教程
随机推荐
博客目录
Node-1.高性能服务器
梅科尔工作室-HarmonyOS应用开发第三次培训
Node-2.垃圾回收机制
安全帽识别系统-解决监管难题
Toolbar 和 DrawerLayout 滑动菜单
解决jupyter中import torch出错问题
Solutions to the 7th Jimei University Programming Contest (Individual Contest)
Toward a Unified Model
动画(其二)
架构设计杂谈
Hardhat Recognition System - Solving Regulatory Conundrums
电商机会:私域
跨应用间调用: URL Scheme
CMT2380F32模块开发5-CLK例程
Safety helmet recognition system
从概念认识AI
Diagnostic Log and Trace——dlt的编译和安装
Maykel Studio - Django Web Application Framework + MySQL Database Fourth Training
CMT2380F32模块开发0-总览