public ClientRateLimitMiddleware(RequestDelegate next, RateLimitOptions options, RateLimitProcessor processor ) { _next = next; _options = options; _processor = processor; }
/// <summary> /// Create a new instance /// </summary> /// <param name="next"></param> /// <param name="processor"></param> /// <param name="loggerFactory"></param> public RateLimitMiddleware(RequestDelegate next, RateLimitProcessor <HttpContext> processor, ILoggerFactory loggerFactory) { if (processor == null) { throw new ArgumentNullException("RateLimitProcessor is null."); } _next = next; _loggerFactory = loggerFactory; _processor = processor; }
/// <summary> /// 构造函数 /// </summary> /// <param name="processor"></param> public RateLimitHandler(RateLimitProcessor <HttpRequestMessage> processor) { _processor = processor; }
public static void Main(string[] args) { Console.WriteLine("FireflySoft.RateLimit.Core.Sample"); IRateLimitStorage storage = new InProcessMemoryStorage(); //IRateLimitStorage storage = new RedisStorage(StackExchange.Redis.ConnectionMultiplexer.Connect("127.0.0.1")); var fixedWindowRules = new FixedWindowRateLimitRule <SimulationRequest>[] { new FixedWindowRateLimitRule <SimulationRequest>() { Id = "1", StatWindow = TimeSpan.FromSeconds(1), LimitNumber = 30, ExtractTarget = (request) => { return(request.RequestResource); }, CheckRuleMatching = (request) => { return(true); }, } }; var algorithm = new FixedWindowAlgorithm <SimulationRequest>(fixedWindowRules, true); var processor = new RateLimitProcessor <SimulationRequest> .Builder() .WithAlgorithm(algorithm) .WithStorage(storage) .WithError(new RateLimitError() { Code = 429, }) .Build(); for (int i = 0; i < 80; i++) { var result = processor.Check(new SimulationRequest() { RequestId = Guid.NewGuid().ToString(), RequestResource = "home", Parameters = new Dictionary <string, string>() { { "from", "sample" }, } }); if (i == 40) { algorithm.UpdateRules(new FixedWindowRateLimitRule <SimulationRequest>[] { new FixedWindowRateLimitRule <SimulationRequest>() { Id = "1", StatWindow = TimeSpan.FromSeconds(1), LimitNumber = 60, ExtractTarget = (request) => { return(request.RequestResource); }, CheckRuleMatching = (request) => { return(true); }, } }); } if (i == 60) { algorithm.UpdateRules(new FixedWindowRateLimitRule <SimulationRequest>[] { new FixedWindowRateLimitRule <SimulationRequest>() { Id = "1", StatWindow = TimeSpan.FromSeconds(1), LimitNumber = 40, ExtractTarget = (request) => { return(request.RequestResource); }, CheckRuleMatching = (request) => { return(true); }, } }); } Console.WriteLine($"[{i}]check result:{result.IsLimit}."); } Console.Read(); }
/// <summary> /// Using rate limit processor /// </summary> /// <param name="builder"></param> /// <param name="processor"></param> /// <returns></returns> public static IApplicationBuilder UseRateLimit(this IApplicationBuilder builder, RateLimitProcessor <HttpContext> processor) { return(builder.UseMiddleware <RateLimitMiddleware>(processor)); }