WebApiThrottle限流框架


一、WebApiThrottle限流框架

1、Nuget安裝(PM)

PM> Install-Package WebApiThrottle

WebApiThrottle支持自定義配置各種限流策略。可以根據不同場景配置多個不同的限制,比如授權某個IP每秒、每分鍾、每小時、每天、每周的最大調用次數。 這些限制策略可以配置在所有請求上,也可以單獨給每個API接口去配置。

2、WebApiConfig 增加

            //WebApiConfig 增加
            config.MessageHandlers.Add(new ThrottlingHandler()
            {
                Policy = new ThrottlePolicy(
                    perSecond: 1            //可選參數 每秒限制次數
                    , perMinute: 20         //可選參數 每分鍾限制次數
                    , perHour: 200          //可選參數 每小時限制次數
                    , perDay: 1500          //可選參數 每天限制次數
                    , perWeek: 3000         //可選參數 每周限制次數
                    )
                {
                    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);
                }
            });

然后在新建的控制內添加請求的Action==http://localhost:60288/api/temp

        public IEnumerable<string> Get()
        {
            yield return DateTime.Now.ToString();
        }

默認情況下,被拒絕的請求不會累加到WebApiThrottle的計數器里。 比如一個客戶端在同一秒中請求了3次,而你配置的限制策略是每秒1次,那么分鍾、小時、天的計數器只會記錄第一次調用,因為第一次請求不會被拒絕。如果你想把被拒絕的請求也計算到其他的計數器里(分鍾、小時、天),你可以設置StackBlockedRequests為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特性配置限制頻率-圍繞controllers和actions去自定義頻率限制)

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

 


免責聲明!

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



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