当前位置:首页 > Windows程序 > 正文

WebApiThrottle限流框架使用手册

2021-03-29 Windows程序

介绍

为了防止网站意外暴增的流量比如活动、秒杀、攻击等,导致整个系统瘫痪,在前后端接口服务处进行流量限制是非常有必要的。本篇主要介绍下Net限流框架WebApiThrottle的使用。

WebApiThrottle是一个专门为webApi限制请求频率而设计的,支持寄宿OWIN上的中间件的限制过滤。服务端接口可以基于客户端请求IP地址、客户端请求key、及请求路由去限制webapi接口的访问频率。

使用nuget命令安装WebApiThrottle:

PM> Install-Package WebApiThrottle

Nuget地址:

https://www.nuget.org/packages/WebApiThrottle/

WebApiThrottle支持自定义配置各种限流策略。可以根据不同场景配置多个不同的限制,比如授权某个IP每秒、每分钟、每小时、每天、每周的最大调用次数。 这些限制策略可以配置在所有请求上,也可以单独给每个API接口去配置。

基于IP全局限流

下面的代码是限制来自同IP请求的最大次数。如果在一分钟内,同样IP的客户端分别调用api/values和api/values/1两个接口, 那么调用api/values/1的请求会被拒绝掉。

public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MessageHandlers.Add(new ThrottlingHandler() { Policy = new ThrottlePolicy(perSecond: 1, perMinute: 20, perHour: 200, perDay: 1500, perWeek: 3000) { IpThrottling = true }, Repository = new CacheRepository() }); } }

如果是自寄宿在Owin上的WebApi,上面的CacheRepository必须替换成运行时的MemoryCacheRepository类,因为CacheRepository使用的是Asp.net版本的缓存。

public class Startup { public void Configuration(IAppBuilder appBuilder) { // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); //Register throttling handler config.MessageHandlers.Add(new ThrottlingHandler() { Policy = new ThrottlePolicy(perSecond: 1, perMinute: 20, perHour: 200, perDay: 1500, perWeek: 3000) { IpThrottling = true }, Repository = new MemoryCacheRepository() }); appBuilder.UseWebApi(config); } }

基于IP的端点限流

上面的api/values限流配置会对整个api/values开头的API限流,同一秒内、同一ip访问api/values后,所有后续访问api/values/xxx的请求都会被拒绝掉。 如果配置了端点限流,同一秒内你也访问api/values/1了,请求将不会被拒绝,因为它们走的是不同的路由。

config.MessageHandlers.Add(new ThrottlingHandler() { Policy = new ThrottlePolicy(perSecond: 1, perMinute: 30) { IpThrottling = true, EndpointThrottling = true }, Repository = new CacheRepository() });

基于IP和客户端key的端点限流

如果同一个ip的客户端,在同一秒内,调用了2次api/values,其最后一次的调用将会被拒绝掉。

如果想接口通过唯一key去识别限制客户端,忽略客户端的ip地址限制,应该配置IpThrottling为false。

config.MessageHandlers.Add(new ThrottlingHandler() { Policy = new ThrottlePolicy(perSecond: 1, perMinute: 30) { IpThrottling = true, ClientThrottling = true, EndpointThrottling = true }, Repository = new CacheRepository() });

IP和客户端key的白名单

如果请求是从一个白名单中的IP或客户端key发起的,那么限流策略将不会生效,这个请求的所有信息也不会被存储。 其IP白名单列表支持IP v4和v6的范围配置,比如"192.168.0.0/24", "fe80::/10" 和 "192.168.0.0-192.168.0.255",关于IP范围的更多信息请查看

config.MessageHandlers.Add(new ThrottlingHandler() { Policy = new ThrottlePolicy(perSecond: 2, perMinute: 60) { IpThrottling = true, IpWhitelist = new List<string> { "::1", "192.168.0.0/24" }, ClientThrottling = true, ClientWhitelist = new List<string> { "admin-key" } }, Repository = new CacheRepository() });

IP和客户端key自定义限制频率

你可以自定义基于ip或客户端key的请求频率限制,这些限制会重写WebApiThrottle的默认配置。

需要注意的是,这些自定义策略需要写到全局配置里才会生效,策略里可以单独给某个ip或某个key配置限流策略。

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69514.html