超级大白 发表于 2024-3-6 09:05:40

实时监控.NET Core请求次数:创建记录最近5分钟的请求,轻松可靠

 
概述:在.NET Core中,通过创建RequestCountMiddleware中间件,结合MemoryCache,实现了记录最近5分钟请求次数的功能。该中间件在每个请求中更新计数,并使用缓存存储,为简单而实用的请求监控提供了一个示例。
要实现一个在.NET Core中记录最近5分钟请求次数的RequestCountMiddleware,你可以按照以下步骤操作。在这个例子中,我们将使用MemoryCache来存储请求计数。

[*]创建中间件类:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Threading.Tasks;

public class RequestCountMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IMemoryCache _memoryCache;

    public RequestCountMiddleware(RequestDelegate next, IMemoryCache memoryCache)
    {
      _next = next ?? throw new ArgumentNullException(nameof(next));
      _memoryCache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache));
    }

    public async Task InvokeAsync(HttpContext context)
    {
      // 获取当前时间的分钟部分,以便将请求计数与时间关联
      var currentMinute = DateTime.UtcNow.ToString("yyyyMMddHHmm");

      // 从缓存中获取当前分钟的请求计数,如果不存在则初始化为0
      var requestCount = _memoryCache.GetOrCreate(currentMinute, entry =>
      {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
            return 0;
      });

      // 增加请求计数
      requestCount++;

      // 更新缓存中的请求计数
      _memoryCache.Set(currentMinute, requestCount);

      // 执行下一个中间件
      await _next(context);
    }
}
[*]在Startup.cs中注册中间件:
在ConfigureServices方法中注册MemoryCache服务,并在Configure方法中使用UseMiddleware添加RequestCountMiddleware。
using Microsoft.Extensions.DependencyInjection;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
      // 注册MemoryCache服务
      services.AddMemoryCache();
    }

    public void Configure(IApplicationBuilder app)
    {
      // 添加RequestCountMiddleware到中间件管道
      app.UseMiddleware<RequestCountMiddleware>();

      // 其他中间件...
    }
}
[*]使用中间件:
现在,RequestCountMiddleware将在每个请求中记录最近5分钟的请求次数。 测试代码
   
    ")]
    public class TestController : ControllerBase
    {

      private readonly IMemoryCache _memoryCache;

      public TestController(IMemoryCache memoryCache)
      {
            _memoryCache = memoryCache;
      }

      public IActionResult Index()
      {
            var currentMinute = DateTime.UtcNow.ToString("yyyyMMddHHmm");

            // 从缓存中获取当前分钟的请求计数,如果不存在则初始化为0
            var requestCount = _memoryCache.Get<int>(currentMinute);
            return Ok($"5分钟内访问次数:{requestCount}次");
      }
    }运行效果:
 
请注意,这个示例使用MemoryCache来存储请求计数,这意味着计数将在应用程序重新启动时重置。如果需要持久性,可以考虑使用其他存储方式,如数据库。
源代码获取:
https://pan.baidu.com/s/1To2txIo9VDH2myyM4ecRhg?pwd=6666
 



来源:https://www.cnblogs.com/hanbing81868164/p/18055693
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 实时监控.NET Core请求次数:创建记录最近5分钟的请求,轻松可靠