WebApiThrottle限流框架

ASP.NET Web API Throttling handler is designed to control the rate of requests that clients can make to a Web API based on IP address, client API key and request route. WebApiThrottle is compatible with Web API v2 and can be installed via NuGet, the package is available atnuget.org/packages/WebApiThrottle.

Web API throttling can be configured using the built-in ThrottlePolicy. You can set multiple limits for different scenarios like allowing an IP or Client to make a maximum number of calls per second, per minute, per hour or even per day. You can define these limits to address all requests made to an API or you can scope the limits to each API route.

Global throttling based on IP

The setup bellow will limit the number of requests originated from the same IP.
If from the same IP, in same second, you’ll make a call to api/values and api/values/1 the last call will get blocked.

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

If you are self-hosting WebApi with Owin, then you’ll have to switch to MemoryCacheRepository that uses the runtime memory cache instead of CacheRepository that uses ASP.NET cache.

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host.
        HttpConfiguration config = new HttpConfiguration();

        //Register throttling handler
        config.MessageHandlers.Add(new ThrottlingHandler()
        {
            Policy = new ThrottlePolicy(perSecond: 1, perMinute: 20,
            perHour: 200, perDay: 1500, perWeek: 3000)
            {
                IpThrottling = true
            },
            Repository = new MemoryCacheRepository()
        });

        appBuilder.UseWebApi(config);
    }
}

Endpoint throttling based on IP

If, from the same IP, in the same second, you’ll make two calls to api/values, the last call will get blocked.
But if in the same second you call api/values/1 too, the request will go through because it’s a different route.

config.MessageHandlers.Add(new ThrottlingHandler()
{
    Policy = new ThrottlePolicy(perSecond: 1, perMinute: 30)
    {
        IpThrottling = true,
        EndpointThrottling = true
    },
    Repository = new CacheRepository()
});

Endpoint throttling based on IP and Client Key

If a client (identified by an unique API key) from the same IP, in the same second, makes two calls toapi/values, then the last call will get blocked.
If you want to apply limits to clients regardless of their IPs then you should set IpThrottling to false.

config.MessageHandlers.Add(new ThrottlingHandler()
{
    Policy = new ThrottlePolicy(perSecond: 1, perMinute: 30)
    {
        IpThrottling = true,
        ClientThrottling = true,
        EndpointThrottling = true
    },
    Repository = new CacheRepository()
});

IP and/or Client Key White-listing

If requests are initiated from a white-listed IP or Client, then the throttling policy will not be applied and the requests will not get stored. The IP white-list supports IP v4 and v6 ranges like “192.168.0.0/24″, “fe80::/10″ and “192.168.0.0-192.168.0.255″ for more information check jsakamoto/ipaddressrange.

config.MessageHandlers.Add(new ThrottlingHandler()
{
    Policy = new ThrottlePolicy(perSecond: 2, perMinute: 60)
    {
        IpThrottling = true,
        IpWhitelist = new List<string> { "::1", "192.168.0.0/24" },

        ClientThrottling = true,
        ClientWhitelist = new List<string> { "admin-key" }
    },
    Repository = new CacheRepository()
});

IP and/or Client Key custom rate limits

You can define custom limits for known IPs or Client Keys, these limits will override the default ones. Be aware that a custom limit will only work if you have defined a global counterpart.

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 } }
        },

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

Endpoint custom rate limits

You can also define custom limits for certain routes, these limits will override the default ones.
You can define endpoint rules by providing relative routes like api/entry/1 or just a URL segment like/entry/.
The endpoint throttling engine will search for the expression you’ve provided in the absolute URI,
if the expression is contained in the request route then the rule will be applied.
If two or more rules match the same URI then the lower limit will be applied.

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 { PerScond = 10, PerMinute = 100, PerHour = 1000 } }
        }
    },
    Repository = new CacheRepository()
});

Stack rejected requests

By default, rejected calls are not added to the throttle counter. If a client makes 3 requests per second
and you’ve set a limit of one call per second, the minute, hour and day counters will only record the first call, the one that wasn’t blocked.
If you want rejected requests to count towards the other limits, you’ll have to setStackBlockedRequests to true.

config.MessageHandlers.Add(new ThrottlingHandler()
{
    Policy = new ThrottlePolicy(perSecond: 1, perMinute: 30)
    {
        IpThrottling = true,
        ClientThrottling = true,
        EndpointThrottling = true,
        StackBlockedRequests = true
    },
    Repository = new CacheRepository()
});

Define rate limits in web.config or app.config

WebApiThrottle comes with a custom configuration section that lets you define the throttle policy as xml.

config.MessageHandlers.Add(new ThrottlingHandler()
{
    Policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()),
    Repository = new CacheRepository()
});

Config example (policyType values are 1 – IP, 2 – ClientKey, 3 – Endpoint):

<configuration>

  <configSections>
    <section name="throttlePolicy"
             type="WebApiThrottle.ThrottlePolicyConfiguration, WebApiThrottle" />
  </configSections>

  <throttlePolicy limitPerSecond="1"
                  limitPerMinute="10"
                  limitPerHour="30"
                  limitPerDay="300"
                  limitPerWeek ="1500"
                  ipThrottling="true"
                  clientThrottling="true"
                  endpointThrottling="true">
    <rules>
      <add policyType="1" entry="::1/10"
           limitPerSecond="2"
           limitPerMinute="15"/>
      <add policyType="1" entry="192.168.2.1"
           limitPerMinute="12" />
      <add policyType="2" entry="api-client-key-1"
           limitPerHour="60" />
      <add policyType="3" entry="api/values"
           limitPerDay="120" />
    </rules>
    <whitelists>
      <add policyType="1" entry="127.0.0.1" />
      <add policyType="1" entry="192.168.0.0/24" />
      <add policyType="2" entry="api-admin-key" />
    </whitelists>
  </throttlePolicy>

</configuration>

Retrieving API Client Key

By default, the ThrottlingHandler retrieves the client API key from the “Authorization-Token” request header value.
If your API key is stored differently, you can override the ThrottlingHandler.SetIndentity function and specify your own retrieval method.

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

Storing throttle metrics

WebApiThrottle stores all request data in-memory using ASP.NET Cache when hosted in IIS or Runtime MemoryCache when self-hosted with Owin. If you want to change the storage to
Velocity, MemCache or a NoSQL database, all you have to do is create your own repository by implementing the IThrottleRepository interface.

public interface IThrottleRepository
{
    bool Any(string id);

    ThrottleCounter? FirstOrDefault(string id);

    void Save(string id, ThrottleCounter throttleCounter, TimeSpan expirationTime);

    void Remove(string id);

    void Clear();
}

Logging throttled requests

If you want to log throttled requests you’ll have to implement IThrottleLogger interface and provide it to the ThrottlingHandler.

public interface IThrottleLogger
{
    void Log(ThrottleLogEntry entry);
}

Logging implementation example with ITraceWriter

public class TracingThrottleLogger : IThrottleLogger
{
    private readonly ITraceWriter traceWriter;

    public TracingThrottleLogger(ITraceWriter traceWriter)
    {
        this.traceWriter = traceWriter;
    }

    public void Log(ThrottleLogEntry entry)
    {
        if (null != traceWriter)
        {
            traceWriter.Info(entry.Request, "WebApiThrottle",
                "{0} Request {1} from {2} has been throttled (blocked), quota {3}/{4} exceeded by {5}",
                entry.LogDate,
                entry.RequestId,
                entry.ClientIp,
                entry.RateLimit,
                entry.RateLimitPeriod,
                entry.TotalRequests);
        }
    }
}

Logging usage example with SystemDiagnosticsTraceWriter

var traceWriter = new SystemDiagnosticsTraceWriter()
{
    IsVerbose = true
};
config.Services.Replace(typeof(ITraceWriter), traceWriter);
config.EnableSystemDiagnosticsTracing();

config.MessageHandlers.Add(new ThrottlingHandler()
{
    Policy = new ThrottlePolicy(perSecond: 1, perMinute: 30)
    {
        IpThrottling = true,
        ClientThrottling = true,
        EndpointThrottling = true
    },
    Repository = new CacheRepository(),
    Logger = new TracingThrottleLogger()
});

About

WebApiThrottle is open sourced and MIT licensed, the project is hosted on GitHub atgithub.com/stefanprodan/WebApiThrottle, for questions regarding throttling or any problems you’ve encounter please submit an issue on GitHub.

时间: 2024-08-10 23:29:45

WebApiThrottle限流框架的相关文章

WebApiThrottle限流框架使用手册

阅读目录: 介绍 基于IP全局限流 基于IP的端点限流 基于IP和客户端key的端点限流 IP和客户端key的白名单 IP和客户端key自定义限制频率 端点自定义限制频率 关于被拒请求的计数器 在web.config或app.config中定义限制策略 获取API的客户端key 存储限流的数据 运行期间更新限制频率 限流的请求日志 用ThrottlingFilter.EnableThrottlingAttribute特性配置限制频率 关于ThrottlingMiddleware限制频率 介绍 为

【Dnc.Api.Throttle】适用于.Net Core WebApi接口限流框架

Dnc.Api.Throttle    适用于Dot Net Core的WebApi接口限流框架 使用Dnc.Api.Throttle可以使您轻松实现WebApi接口的限流管理.Dnc.Api.Throttle支持IP.用户身份.Request Header.Request QueryString等多种限流策略,支持黑名单和白名单功能,支持全局拦截和单独Api拦截. Dnc.Api.Throttle暂时只支持Redis作为缓存和存储库,后续会进行扩展. 开始使用 安装Dnc.Api.Thrott

控制ASP.NET Web API 调用频率与限流

ASP.NET MVC 实现 https://github.com/stefanprodan/MvcThrottle ASP.NET WEBAPI 实现 https://github.com/stefanprodan/WebApiThrottle   Refer: Throttling ASP.NET Web API calls http://blog.maartenballiauw.be/post/2013/05/28/Throttling-ASPNET-Web-API-calls.aspx

Sentinel如何通过限流实现服务的高可用性

摘要: 在复杂的生产环境下可能部署着成千上万的服务实例,当流量持续不断地涌入,服务之间相互调用频率陡增时,会产生系统负载过高.网络延迟等一系列问题,从而导致某些服务不可用.如果不进行相应的流量控制,可能会导致级联故障,并影响到服务的可用性,因此如何对高流量进行合理控制,成为保障服务稳定性的关键. 在复杂的生产环境下可能部署着成千上万的服务实例,当流量持续不断地涌入,服务之间相互调用频率陡增时,会产生系统负载过高.网络延迟等一系列问题,从而导致某些服务不可用.如果不进行相应的流量控制,可能会导致级

大型网站限流算法的实现和改造

最近写了一个限流的插件,所以避免不了的接触到了一些限流算法.本篇文章就来分析一下这几种常见的限流算法 分析之前 依我个人的理解来说限流的话应该灵活到可以针对每一个接口来做.比如说一个类里面有5个接口,那么我的限流插件就应该能针对每一个接口就行不同的限流方案.所以呢,既然针对的每个接口所以就需要一个可以唯一标示这个接口的key(我取的是类名+方法名+入参). 分布式限流强烈推荐使用redis+lua或者nginx+lua来实现. 这里用2个限流条件来做示例讲一下常见的限流算法: 接口1它10秒钟最

微服务架构下的分布式限流方案思考

1.微服务限流 随着微服务的流行,服务和服务之间的稳定性变得越来越重要.缓存.降级和限流是保护微服务系统运行稳定性的三大利器.缓存的目的是提升系统访问速度和增大系统能处理的容量,而降级是当服务出问题或者影响到核心流程的性能则需要暂时屏蔽掉,待高峰或者问题解决后再打开,而有些场景并不能用缓存和降级来解决,比如稀缺资源.数据库的写操作.频繁的复杂查询,因此需有一种手段来限制这些场景的请求量,即限流. 比如当我们设计了一个函数,准备上线,这时候这个函数会消耗一些资源,处理上限是1秒服务3000个QPS

Spring Cloud微服务安全实战_4-10_用spring-cloud-zuul-ratelimit做限流

本篇讲网关上的限流 用开源项目spring-cloud-zuul-ratelimit 做网关上的限流 (项目github:https://github.com/marcosbarbero/) 1,在网关项目里,引入限流组件的maven依赖: 2,在网关项目yml配置里,配限流相关配置 github也有相关配置说明:https://github.com/marcosbarbero/spring-cloud-zuul-ratelimit 限流框架限流需要存一些信息,可以存在数据库里,也可以存在red

DRF框架中其他功能:认证、权限、限流

定义视图时,只要视图继承了APIView或其子类,就可以使用DRF框架的认证.权限和限流功能. 当客户端访问API接口时,DRF框架在调用对应的API接口之前,会依次进行认证.权限和限流的操作. 认证Authentication 权限Permissions 限流Throttling 原文地址:https://www.cnblogs.com/oklizz/p/11290731.html

Hystrix分布式系统限流、降级、熔断框架(二)

三.Hystrix容错 ???????Hystrix的容错主要是通过添加容许延迟和容错方法,帮助控制这些分布式服务之间的交互. 还通过隔离服务之间的访问点,阻止它们之间的级联故障以及提供回退选项来实现这一点,从而提高系统的整体弹性.Hystrix主要提供了以下几种容错方法: 资源隔离 熔断 降级 1.资源隔离-线程池 2.资源隔离-信号量 线程池和信号量隔离比较 ? 线程切换 支持异步 支持超时 支持熔断 限流 开销 信号量 否 否 否 是 是 小 线程池 是 是 是 是 是 大 ???????