webapi限流框架WebApiThrottle

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

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

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

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

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()
        });
    }
}
config.MessageHandlers.Add(new ThrottlingHandler()
{
    Policy = new ThrottlePolicy(perSecond: 1, perMinute: 20, perHour: 200, perDay: 1500)
    {
        IpThrottling = true,
        IpRules = new Dictionary<string, RateLimits>
        { 
            { "192.168.1.1", new RateLimits { PerSecond = 2 } },
            { "192.168.2.0/24", new RateLimits { PerMinute = 30, PerHour = 30*60, PerDay = 30*60*24 } }
        },

        ClientThrottling = true,
        ClientRules = new Dictionary<string, RateLimits>
        { 
            { "api-client-key-1", new RateLimits { PerMinute = 40, PerHour = 400 } },
            { "api-client-key-9", new RateLimits { PerDay = 2000 } }
        }
    },
    Repository = new CacheRepository()
});

 

 

用ThrottlingFilter、EnableThrottlingAttribute特性配置限制频率

EnableThrottling与ThrottlingHandler是一个二选一的策略配置方案,二者会做同样的事情,但ThrottlingHandler可以通过EnableThrottlingAttribute特性指定某个webapi的controllers和actions去自定义频率限制。需要注意的是,在webapi请求管道中,ThrottlingHandler是在controller前面执行,因此在你不需要ThrottlingFilter提供的功能时,可以用ThrottlingHandler去直接替代它。

设置ThrottlingFilter过滤器的步骤,跟ThrottlingHandler类似

 public static class WebApiConfig
    { 
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
      

            config.SuppressDefaultHostAuthentication();

           
            config.Filters.Add(new CustomerThrottlingFilter()
            {
                Policy = new ThrottlePolicy(perMinute: 15)
                {
                    //scope to IPs
                    IpThrottling = false,

                    //scope to clients (if IP throttling is applied then the scope becomes a combination of IP and client key)
                    ClientThrottling = true,

                    //white list API keys that don’t require throttling
                    ClientWhitelist = new List<string> { "admin-ll" },

                    //Endpoint rate limits will be loaded from EnableThrottling attribute
                    EndpointThrottling = true
                }
            });

 

        }
    }

获取API的客户端key

默认情况下,WebApiThrottle的ThrottlingHandler(限流处理器)会从客户端请求head里通过Authorization-Token key取值。如果你的API key存储在不同的地方,你可以重写ThrottlingHandler.SetIndentity方法,指定你自己的取值策略。

public class CustomThrottlingHandler : ThrottlingHandler
{
    protected override RequestIdentity SetIndentity(HttpRequestMessage request)
    {
        return new RequestIdentity()
        {
            ClientKey = request.Headers.Contains("Authorization-Key") ? request.Headers.GetValues("Authorization-Key").First() : "anon",
            ClientIp = base.GetClientIp(request).ToString(),
            Endpoint = request.RequestUri.AbsolutePath.ToLowerInvariant()
        };
    }
}

 

posted @ 2017-11-30 10:17  桃花雪  阅读(2853)  评论(0编辑  收藏  举报