我有一个单例 ActionFilter,我想将数据存储在缓存中。我做了什么:
程序.cs
builder.Services.AddSingleton<MyActionFilter>();
builder.Services.AddMemoryCache();
动作过滤器
public class MyActionFilter : ActionFilterAttribute
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IMemoryCache _cache;
public MyActionFilter(IServiceScopeFactory serviceScopeFactory, IMemoryCache cache)
{
_serviceScopeFactory = serviceScopeFactory;
_cache = cache;
}
获取
if (_cache.TryGetValue(token, out int temp))
{
await next.Invoke();
return;
}
设置
if (response.Success)
{
if (response.Score >= _minimumAllowedScore)
{
_cache.Set(token, response.Score, new TimeSpan(0, _expirationMinutes, 0));
await next.Invoke();
return;
}
它设置了值,但在下一个请求中无法通过相同的键找到它,计数显示有一个条目(应该如此)。我究竟做错了什么?另外,如果我有 5 rps max,使用单例动作过滤器是否会影响性能?