实时监控.NET Core请求次数:创建记载最近5分钟的请求,轻松可靠
https://p3-sign.toutiaoimg.com/tos-cn-i-axegupay5k/539fc515a4db48a89ce4da37c57bc025~noop.image?_iz=58558&from=article.pc_detail&lk3s=953192f4&x-expires=1710287278&x-signature=MNes9CH2IQo3DbiO6V%2F38vkSCLo%3D概述:在.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}次");
}
}运行效果:
https://p3-sign.toutiaoimg.com/tos-cn-i-6w9my0ksvp/57fbd9d2483d4a26960ba8fbce3f3f51~noop.image?_iz=58558&from=article.pc_detail&lk3s=953192f4&x-expires=1710287278&x-signature=7VHUrxsA%2FCHju00QUIBnhO7Rm4s%3D
请留意,这个示例使用MemoryCache来存储请求计数,这意味着计数将在应用程序重新启动时重置。如果须要持久性,可以考虑使用其他存储方式,如数据库。
源代码获取:
https://pan.baidu.com/s/1To2txIo9VDH2myyM4ecRhg?pwd=6666
https://img2024.cnblogs.com/blog/2113279/202403/2113279-20240306074926647-2069448297.gif
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]