当前位置:网站首页>.Net Core 限流控制-AspNetCoreRateLimit
.Net Core 限流控制-AspNetCoreRateLimit
2022-04-23 03:02:00 【dotNET跨平台】
简介
AspNetCoreRateLimit是ASP.NET核心速率限制框架,能够对WebApi,Mvc中控制限流,AspNetCoreRateLimit包包含IpRateLimit中间件和ClientRateLimit中间件,每个中间件都可以为不同的场景设置多个限,该框架的作者是stefanprodan,项目nuget地址是https://github.com/stefanprodan/AspNetCoreRateLimit。
IpRateLimitMiddleware(Github: AspNetCoreRateLimit) 是ASPNETCore的一个限流的中间件,用于控制客户端调用API的频次, 如果客户端频繁访问服务器,可以限制它的频率,已降低访问服务器端的压力。或者如果有爬虫在爬取关键数据,也可以限制某个/某些API或者某些IP的每天调取次数, 这样限制他爬取的速度。
使用方法
NuGet 安装:
Install-Package AspNetCoreRateLimit
Install-Package AspNetCoreRateLimit.Redis
Startup.cs 代码:
public void ConfigureServices(IServiceCollection services)
{
// needed to load configuration from appsettings.json
services.AddOptions();
// needed to store rate limit counters and ip rules
services.AddMemoryCache();
//load general configuration from appsettings.json
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
//load ip rules from appsettings.json
services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));
// inject counter and rules stores
services.AddInMemoryRateLimiting();
//services.AddDistributedRateLimiting<AsyncKeyLockProcessingStrategy>();
//services.AddDistributedRateLimiting<RedisProcessingStrategy>();
//services.AddRedisRateLimiting();
// Add framework services.
services.AddMvc();
// configuration (resolvers, counter key builders)
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseIpRateLimiting();
app.UseMvc();
}
您应该在注册任何其他组件之前注册中间件。
如果你对应用程序进行负载平衡,你需要将IDistributedCache与Redis或SQLServer一起使用,以便所有kestrel实例都具有相同的速率限制存储。您应该像这样注入分布式存储,而不是内存存储:
// inject counter and rules distributed cache stores
services.AddSingleton<IIpPolicyStore, DistributedCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore,DistributedCacheRateLimitCounterStore>();
配置和一般规则应用程序设置appsettings.json::
"IpRateLimiting": {
"EnableEndpointRateLimiting": false,
"StackBlockedRequests": false,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"HttpStatusCode": 429,
"IpWhitelist": [ "127.0.0.1", "::1/10", "192.168.0.0/24" ],
"EndpointWhitelist": [ "get:/api/license", "*:/api/status" ],
"ClientWhitelist": [ "dev-id-1", "dev-id-2" ],
"GeneralRules": [
{
"Endpoint": "*",
"Period": "1s",
"Limit": 2
},
{
"Endpoint": "*",
"Period": "15m",
"Limit": 100
},
{
"Endpoint": "*",
"Period": "12h",
"Limit": 1000
},
{
"Endpoint": "*",
"Period": "7d",
"Limit": 10000
}
]
}
如果EnableEndpointRateLimiting设置为false,则限制将全局应用,并且只有作为endpoint*的规则将应用。例如,如果设置每秒5次调用的限制,则对任何端点的任何HTTP调用都将计入该限制。
如果EnableEndpointRateLimiting设置为true,则限制将应用于每个端点,如{HTTP\u Verb}{PATH}。例如,如果为*:/api/values设置每秒5次调用的限制,客户端可以每秒调用5次GET/api/values,但也可以调用5次PUT/api/values。
如果StackBlockedRequests设置为false,则拒绝的呼叫不会添加到油门计数器。如果一个客户端每秒发出3个请求,而您已将限制设置为每秒一个呼叫,那么其他限制(如每分钟或每天计数器)将只记录未被阻止的第一个呼叫。如果希望拒绝的请求计入其他限制,则必须将StackBlockedRequests设置为true。
当Kestrel服务器位于反向代理后时,RealiPeader用于提取客户端IP,如果代理使用不同的头,则X-Real-IP使用此选项进行设置。
ClientHeader用于提取白名单的客户端id。如果此标头中存在客户端id,并且与ClientWhitelist中指定的值匹配,则不应用速率限制。
"IpRateLimitPolicies": {
"IpRules": [
{
"Ip": "84.247.85.224",
"Rules": [
{
"Endpoint": "*",
"Period": "1s",
"Limit": 10
},
{
"Endpoint": "*",
"Period": "15m",
"Limit": 200
}
]
},
{
"Ip": "192.168.3.22/25",
"Rules": [
{
"Endpoint": "*",
"Period": "1s",
"Limit": 5
},
{
"Endpoint": "*",
"Period": "15m",
"Limit": 150
},
{
"Endpoint": "*",
"Period": "12h",
"Limit": 500
}
]
}
]
}
IP字段支持IP v4和v6的值和范围,如“192.168.0.0/24”、“fe80::/10”或“192.168.0.0-192.168.0.255”。
版权声明
本文为[dotNET跨平台]所创,转载请带上原文链接,感谢
https://blog.csdn.net/sd7o95o/article/details/124335099
边栏推荐
- Regular object type conversion tool - Common DOM class
- Linux redis - redis ha sentinel cluster construction details & redis master-slave deployment
- Planning code ROS migration POMDP prediction planning (I)
- Liunx foundation - zabbix5 0 monitoring system installation and deployment
- 【工欲善其事必先利其器】论文编辑及文献管理(Endnote,Latex,JabRef ,overleaf)资源下载及使用指南
- Guangcheng cloud service can fill in a daily report regularly every day
- The express project changes the jade template to art template
- Er and eer models
- Huashu "deep learning" and code implementation: 01 Linear Algebra: basic concepts + code implementation basic operations
- ROP Emporium x86_ 64 7 ~ 8 questions
猜你喜欢
How can enterprises with major hazard installations ensure the completion of the digital construction task of double prevention mechanism by the end of the year
Solve the problem that PowerShell mining occupies 100% of cpu7 in win7
ROP Emporium x86_64 7~8题
The interface request takes too long. Jstack observes the lock holding
Golden nine silver ten interview season, you are welcome to take away the interview questions (with detailed answer analysis)
Slave should be able to synchronize with the master in tests/integration/replication-psync.tcl
How to write the expected salary on your resume to double your salary during the interview?
基于ele封装下拉菜单等组件
First knowledge of C language ~ branch statements
Log cutting - build a remote log collection server
随机推荐
Wepy learning record
What is the difference between varchar and char?
L2-006 树的遍历(中后序确定二叉树&层序遍历)
The space between the left and right of the movie ticket seats is empty and cannot be selected
Plug in for vscode
Slave should be able to synchronize with the master in tests/integration/replication-psync. tcl
Niuke white moon race 6 [solution]
Learn regular expression options, assertions
Guangcheng cloud service can fill in a daily report regularly every day
[hcip] detailed explanation of six LSAS commonly used by OSPF
Planning code ROS migration POMDP prediction planning (I)
MySQL complex query uses temporary table / with as (similar to table variable)
Numpy append function
Introduction to ACM [TSP problem]
Log cutting - build a remote log collection server
Some problems encountered in setting Django pure interface, channel and MySQL on the pagoda panel
Source code and some understanding of employee management system based on polymorphism
Basic SQL (VIII) data update operation practice
tf. keras. layers. Embedding function
Shell learning notes -- shell processing of output stream awk