吴五万
robs

导航

 

netcore限流

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;

public class RateLimitMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IMemoryCache _cache;
    private readonly int _limit;
    private readonly TimeSpan _interval;

    public RateLimitMiddleware(RequestDelegate next, IMemoryCache cache, int limit, TimeSpan interval)
    {
        _next = next;
        _cache = cache;
        _limit = limit;
        _interval = interval;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var cacheKey = GetCacheKey(context.Request.Path);
        var requestCount = _cache.GetOrCreate(cacheKey, entry =>
        {
            entry.SetSlidingExpiration(_interval);
            return 0;
        });

        if (requestCount >= _limit)
        {
            context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
            await context.Response.WriteAsync($"Rate limit exceeded. Try again in {_interval.TotalSeconds} seconds.");
        }
        else
        {
            _cache.Set(cacheKey, requestCount + 1, _interval);
            await _next(context);
        }
    }

    private string GetCacheKey(string path)
    {
        return $"ratelimit:{path}";
    }
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMiddleware<RateLimitMiddleware>(limit: 100, interval: TimeSpan.FromMinutes(1));
    // ...
}

这个示例中,将 RateLimitMiddleware 注册为全局 Middleware,并指定最大请求数为 100,限制时间为 1 分钟。

使用 Middleware 实现接口限流可以灵活地控制请求的流量,提高服务的可靠性和稳定性。同时,也可以通过配置不同的参数来适应不同的业务需求。

posted on 2023-03-16 16:51  吴五万  阅读(66)  评论(0编辑  收藏  举报