1. 程式人生 > >WebApiThrottle限流框架——用ThrottlingFilter、EnableThrottlingAttribute特性配置限制頻率

WebApiThrottle限流框架——用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";
    }
}