WebApiThrottle limiting framework

A, WebApiThrottle limiting frame

1, Nuget installation (PM)

PM> Install-Package WebApiThrottle

WebApiThrottle support for custom configuration of various limiting policies. You can configure a number of different scenarios based on different constraints, such as an authorized IP per second, hourly, daily, weekly maximum number of calls per minute. These restrictions can be arranged on all the policy request may be given separately for each API interface to configure.

2, WebApiConfig increase

            // WebApiConfig increase 
            config.MessageHandlers.Add ( new new ThrottlingHandler () 
            { 
                the Policy = new new ThrottlePolicy ( 
                    perSecond: . 1             // number of times per second optional parameter limit 
                    , the perminute: 20 is          // optional parameter limit per minute 
                    , perHour: 200 is           / / optional parameter limit per hour 
                    , perday: 1500           // optional parameter limit times per day 
                    , perWeek: 3000          // optional parameter limiting the number of times per week 
                    ) 
                { 
                    IpThrottling= To true ,    // value indicating whether to enable IP restriction 
                    ClientThrottling = to true  // This value indicates whether to enable client throttling 
                }, 
                the Repository = new new CacheRepository (),
                 // QuotaExceededMessage = JsonConvert.SerializeObject (json.msg), 
                QuotaExceededContent = ( L, obj) =>   // violation limiting event 
                {
                     // var JSON = {a JsonResult new new code = 0, = $ MSG "exceeds a predetermined frequency, obj {L} {}"}; 
                    var JSON = new new   {code = 0 , = $ MSG " exceeds a predetermined frequency, L {} {} obj " }; // anonymous Json 
                    return (JSON); 
                } 
            });

By default, the rejected requests are not accumulated in the counter WebApiThrottle. For example, a client request in the same second three times, and you configure the policy limit is 1 per second, then the minutes, hours, days counter will only record the first call, because the first request would not be rejected . If you want the rejected requests to be calculated in another counter (minutes, hours, days), you can set StackBlockedRequests to true.

config.MessageHandlers.Add(new ThrottlingHandler()
{
    Policy = new ThrottlePolicy(perSecond: 1, perMinute: 30)
    {
        IpThrottling = true,
        ClientThrottling = true,
        EndpointThrottling = true,
        StackBlockedRequests = true //拒绝的请求累加到WebApiThrottle的计数器里        
    },
    Repository = new CacheRepository()
});

 有的时候我们只需要设置一个参数,每分钟限流次数

            //WebApiConfig 增加
            config.MessageHandlers.Add(new ThrottlingHandler()
            {
                Policy = new ThrottlePolicy( perMinute: 5 )//可选参数 我们仅需要每分钟限制次数
                {
                    IpThrottling = true   //该值指示是否启用IP限制
                    ,ClientThrottling = true //该值指示是否启用客户端限制         
                },
                Repository = new CacheRepository(),
                //QuotaExceededMessage = JsonConvert.SerializeObject(json.msg),
                QuotaExceededContent = (l, obj) =>  //违反限流事件
                {
                    //var json = new JsonResult { code = 0, msg = $"超出规定的频率了,{l}{obj}" };
                    var json = new { code = 0, msg = $"超出规定的频率了,{l}{obj}" };//匿名Json
                    return (json);
                }
            });

3、使用方式一(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";
    }
}

4、使用方式二(端点自定义限制频率)

你也可以为明确的路由地址去自定义限制频率,这些限制配置会重写WebApiThrottle的默认配置。也可以通过相关联的路由地址去定义端点的限制规则,比如api/entry/1端点的请求仅仅是/entry/整个路由地址请求的一部分。 配置后,端点限制引擎会在请求的绝对URI中去搜索这个表达式(api/entry/1),如果这个表达式在请求路由策略中被找到,那么这个限制规则将会被应用。如果有两个或更多的限制规则匹配到同一个URL,更近一级的限制策略将会被应用。

config.MessageHandlers.Add(new ThrottlingHandler()
{
    Policy = new ThrottlePolicy(perSecond: 1, perMinute: 20, perHour: 200)
    {
        IpThrottling = true,
        ClientThrottling = true,
        EndpointThrottling = true,
        EndpointRules = new Dictionary<string, RateLimits>
        { 
            { "api/search", new RateLimits { PerSecond = 10, PerMinute = 100, PerHour = 1000 } }
        }
    },
    Repository = new CacheRepository()
});

 

Guess you like

Origin www.cnblogs.com/fger/p/11119566.html