【.NET】WebApiThrottle限流框架(14)——用ThrottlingFilter、EnableThrottlingAttribute特性配置限制频率
·
EnableThrottling与ThrottlingHandler是一个二选一的策略配置方案,二者会做同样的事情,但ThrottlingHandler可以通过EnableThrottlingAttribute特性指定某个webapi的controllers和actions去自定义频率限制。需要注意的是,在webapi请求管道中,ThrottlingHandler是在controller前面执行,因此在你不需要ThrottlingFilter提供的功能时,可以用ThrottlingHandler去直接替代它。
设置ThrottlingFilter过滤器的步骤,跟ThrottlingHandler类似:
config.Filters.Add(new ThrottlingFilter()
{
Policy = new ThrottlePolicy(perSecond: 1, perMinute: 20,
perHour: 200, perDay: 2000, perWeek: 10000)
{
//ip配置区域
IpThrottling = true,
IpRules = new Dictionary<string, RateLimits>
{
{ "::1/10", new RateLimits { PerSecond = 2 } },
{ "192.168.2.1", new RateLimits { PerMinute = 30, PerHour = 30*60, PerDay = 30*60*24 } }
},
//添加127.0.0.1到白名单,本地地址不启用限流策略
IpWhitelist = new List<string> { "127.0.0.1", "192.168.0.0/24" },
//客户端配置区域,如果ip限制也是启动的,那么客户端限制策略会与ip限制策略组合使用。
ClientRules = new Dictionary<string, RateLimits>
{
{ "api-client-key-demo", new RateLimits { PerDay = 5000 } }
},
//白名单中的客户端key不会进行限流。
ClientWhitelist = new List<string> { "admin-key" },
//端点限制策略配置会从EnableThrottling特性中获取。
EndpointThrottling = true
}
});
使用特性开启限流并配置限制频率:
[EnableThrottling(PerSecond = 2)]
public class ValuesController : ApiController
{
[EnableThrottling(PerSecond = 1, PerMinute = 30, PerHour = 100)]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[DisableThrotting]
public string Get(int id)
{
return "value";
}
}
更多推荐
所有评论(0)