为了防止网站意外暴增的流量比如活动、秒杀、攻击等,导致整个系统瘫痪,在前后端接口服务处进行流量限制是非常有必要的。本篇主要介绍下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: , perMinute: , perHour: , perDay: , perWeek: )
{
IpThrottling = true
},
Repository = new CacheRepository()
});
}
}
config.MessageHandlers.Add(new ThrottlingHandler()
{
Policy = new ThrottlePolicy(perSecond: , perMinute: , perHour: , perDay: )
{
IpThrottling = true,
IpRules = new Dictionary<string, RateLimits>
{
{ "192.168.1.1", new RateLimits { PerSecond = } },
{ "192.168.2.0/24", new RateLimits { PerMinute = , PerHour = *, PerDay = ** } }
}, ClientThrottling = true,
ClientRules = new Dictionary<string, RateLimits>
{
{ "api-client-key-1", new RateLimits { PerMinute = , PerHour = } },
{ "api-client-key-9", new RateLimits { PerDay = } }
}
},
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: )
{
//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()
};
}
}

webapi限流框架WebApiThrottle的更多相关文章

  1. WebApiThrottle限流框架使用手册

    阅读目录: 介绍 基于IP全局限流 基于IP的端点限流 基于IP和客户端key的端点限流 IP和客户端key的白名单 IP和客户端key自定义限制频率 端点自定义限制频率 关于被拒请求的计数器 在we ...

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

    Dnc.Api.Throttle    适用于Dot Net Core的WebApi接口限流框架 使用Dnc.Api.Throttle可以使您轻松实现WebApi接口的限流管理.Dnc.Api.Thr ...

  3. 微服务组件--限流框架Spring Cloud Hystrix分析

    Hystrix的介绍 [1]Hystrix是springCloud的组件之一,Hystrix 可以让我们在分布式系统中对服务间的调用进行控制加入一些调用延迟或者依赖故障的容错机制. [2]Hystri ...

  4. WebApiThrottle限流框架

    ASP.NET Web API Throttling handler is designed to control the rate of requests that clients can make ...

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

    ASP.NET MVC 实现 https://github.com/stefanprodan/MvcThrottle ASP.NET WEBAPI 实现 https://github.com/stef ...

  6. Spring Cloud alibaba网关 sentinel zuul 四 限流熔断

    spring cloud alibaba 集成了 他内部开源的 Sentinel 熔断限流框架 Sentinel 介绍 官方网址 随着微服务的流行,服务和服务之间的稳定性变得越来越重要.Sentine ...

  7. ASP.NET Core WebApi AspNetCoreRateLimit 限流中间件学习

    AspNetCoreRateLimit介绍: AspNetCoreRateLimit是ASP.NET核心速率限制框架,能够对WebApi,Mvc中控制限流,AspNetCoreRateLimit包包含 ...

  8. 简易RPC框架-客户端限流配置

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  9. Anno 框架 增加缓存、限流策略、事件总线、支持 thrift grpc 作为底层传输

    github 地址:https://github.com/duyanming/dymDemo dym 分布式开发框架 Demo 熔断 限流 事件总线(包括基于内存的.rabbitmq的) CQRS D ...

随机推荐

  1. HDOJ5883(欧拉路)

    The Best Path Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)Tot ...

  2. SPUtils

    public class SPUtils { /** * 保存在手机里的SP文件名 */ public static final String FILE_NAME = "my_sp" ...

  3. 模拟admin组件自己开发stark组件之创建篇

    admin组件 admin组件为我们提供了针对django管理页面 我们先简短来看下django的admin组件的启动流程,注册流程,url匹配过程 启动注册 1. 扫描所有应用下的注册了应用中的ad ...

  4. abbreviation

    1. ps------process status 2. tty-----teletype 3. ping----packet internet groper 4. nohup-----no hang ...

  5. FBString

    folly/FBString.h fbstring is a drop-in replacement for std::string. The main benefit of fbstring is ...

  6. Druid.io系列(四):索引过程分析

    原文链接: https://blog.csdn.net/njpjsoftdev/article/details/52956083 Druid底层不保存原始数据,而是借鉴了Apache Lucene.A ...

  7. maven将手动下载的jar包安装到本地仓库

    <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave ...

  8. 走了很多弯路的CCScrollView

    最近在学习Cocos2d-x,学习CCScrollView的时候走了很多弯路,决定记录下来. 学习cocos2d-x的最大的困惑就是资料不是很齐全,网上有很多资料,但是版本差异大,其次深度低,讲解不够 ...

  9. 17_java之Integer|System|Arrays|Math|BigInteger|BigDecimal

    01基本数据类型对象包装类概述 *A:基本数据类型对象包装类概述 *a.基本类型包装类的产生 在实际程序使用中,程序界面上用户输入的数据都是以字符串类型进行存储的.而程序开发中,我们需要把字符串数据, ...

  10. Form Data 和 Request Payload 区别

    Form Data 和 Request Payload 区别 如果请求头里设置Content-Type: application/x-www-form-urlencoded,那么这个请求被认为是表单请 ...