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()
        };
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM