FireflySoft.RateLimit
FireflySoft.RateLimit copied to clipboard
在ASP.NET MVC 项目中如何注册限流处理器
很好的库,已经在ASP.NET WEB API 中实现限流。可否告知一下如何在ASP.NET MVC项目模版中注册限流组件。
MVC试过 FireflySoft.RateLimit.AspNet 这个包吗? Global.asax.cs中使用下面这种方式:
protected void Application_Start()
{
...
GlobalConfiguration.Configuration.MessageHandlers.Add(
new RateLimitHandler(
new Core.InProcessAlgorithm.InProcessFixedWindowAlgorithm(
new[] {
new FixedWindowRule()
{
ExtractTarget = context =>
{
return (context as HttpRequestMessage).RequestUri.AbsolutePath;
},
CheckRuleMatching = context =>
{
return true;
},
Name="default limit rule",
LimitNumber=30,
StatWindow=TimeSpan.FromSeconds(1)
}
})
));
...
}
如果不行,则可以在MVC的请求过滤器中自己包装一下,你需要找到MVC的过滤器使用方法,然后在其中增加类似下边的逻辑:
// 算法规则
var fixedWindowRules = new FixedWindowRule[]
{
new FixedWindowRule()
{
Id = "3",
StatWindow=TimeSpan.FromSeconds(1),
LimitNumber=30,
ExtractTarget = (request) =>
{
return (request as SimulationRequest).RequestResource;
},
CheckRuleMatching = (request) =>
{
return true;
},
}
};
// 算法
IAlgorithm algorithm = new InProcessFixedWindowAlgorithm(fixedWindowRules);
// 限流检查
var result = algorithm.Check(new SimulationRequest()
{
RequestId = Guid.NewGuid().ToString(),
RequestResource = "home",
Parameters = new Dictionary<string, string>() {
{ "from","sample" },
}
});
只需要将algorithm.Check的参数替换为MVC的Request,然后处理result返回的限流结果。
你也可以参考下 FireflySoft.RateLimit.AspNet 这个项目的实现方法。
MVC中没有 GlobalConfiguration 类。GlobalConfiguration 类在System.Web.Http.WebHost程序集中。MVC的项目模版中没有引用System.Web.Http.WebHost程序集。
我尝试一下你的第二种方法。