这就是我实现CacheManager的方式。我面临的问题是TryGetValue将始终在RemoveFromCache函数中返回null。在令牌之一过期后调用此函数,因此我试图从缓存中的列表中清除该令牌,而GetAllTokens返回所有令牌的完整列表。 AddTokenToCache工作正常。
它是ASPNET-Core 3.0上的WebAPI
CacheManager.cs
public class CacheManager : ICacheManager
{
private IMemoryCache _cache;
public CacheManager(IMemoryCache cache) {
_cache = cache;
}
public void AddTokenToCache(string appName, string tokenString)
{
List<Token> tokens = new List<Token>();
//save this token against the application record in-memory
if (!_cache.TryGetValue(CacheHelper.CacheKey_Tokens, out tokens))
{
if (tokens == null)
tokens = new List<Token>();
}
tokens.Add(new Token
{
AppName = appName,
GeneratedAt = DateTime.Now,
TokenId = tokenString
});
// Set cache options.
var cacheEntryOptions = new MemoryCacheEntryOptions()
;// .SetSlidingExpiration(TimeSpan.FromSeconds(180)); //3 minutes
_cache.Set(CacheHelper.CacheKey_Tokens, tokens, cacheEntryOptions);
}
public List<Token> GetAllTokens()
{
return _cache.Get<List<Token>>(CacheHelper.CacheKey_Tokens);
}
public bool RemoveFromCache(string tokenId)
{
List<Token> tokens = new List<Token>();
//remove this token from memory
if (!_cache.TryGetValue(CacheHelper.CacheKey_Tokens, out tokens)) {
return false;
}
else
{
if (tokens != null && tokens.Count > 0)
{
//_logger.LogInfo("Processing token");
//trimming quotations from the string
tokenId = tokenId.Substring(1, tokenId.Length - 2);
int index = tokens.FindIndex(t => t.TokenId == tokenId);
if (index >= 0)
tokens.RemoveAt(index);
var cacheEntryOptions = new MemoryCacheEntryOptions();
_cache.Set(CacheHelper.CacheKey_Tokens, tokens, cacheEntryOptions);
return true;
}
}
return false;
}
}
我的通话顺序是:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ILoggerManager, LoggerManager>();
services.AddMemoryCache();
services.AddDbContext<GEContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
services.AddRazorPages();
services.AddSingleton<ICacheManager, CacheManager>();
RegisterHandlerforTokenExpiredEvent(services);
//other code removed for brevity
}
public void RegisterHandlerforTokenExpiredEvent(IServiceCollection services)
{
var sp = services.BuildServiceProvider();
var jwtManager = sp.GetService<IJWTAuthenticationManager>(); //publisher
var cacheManager = sp.GetService<ICacheManager>(); //subscriber
jwtManager.TokenExpired += cacheManager.OnTokenExpired;
}
这是因为您通过ServiceProvider
建立了另一个services.BuildServiceProvider()
:
public void RegisterHandlerforTokenExpiredEvent(IServiceCollection services) { var sp = services.BuildServiceProvider(); // this is a different service provider from the default one built by ASP.NET Core itself. var jwtManager = sp.GetService<IJWTAuthenticationManager>(); //publisher var cacheManager = sp.GetService<ICacheManager>(); //subscriber // it doesn't work because the cacheManager is not the same instance that you use in the controllers jwtManager.TokenExpired += cacheManager.OnTokenExpired; }
结果,您获得的ICacheManager
实例是您在Controllers / Other Services中注入的NOt the same singleton。换句话说,您将有两个不同的ICacheManager
实例!
作为一个黄金法则,DO NOT在您的应用程序层代码中通过services.BuildServiceProvider()
生成ServiceProvider的另一个副本,除非您确定它适合您。
似乎您的JWTAuthenticationManager
是单例,并且您想在启动时绑定事件处理程序。如果是这种情况,您可以注册一个HostedService。
public class MyHostedService : IHostedService
{
private readonly IJWTAuthenticationManager _jWTAuthManager;
private readonly ICacheManager _cacheManager;
// suppose your IJWTAuthenticationManager is a singleton service
public MyHostedService(IJWTAuthenticationManager jWTAuthManager, ICacheManager cacheManager)
{
this._jWTAuthManager = jWTAuthManager;
this._cacheManager = cacheManager;
}
public Task StartAsync(CancellationToken cancellationToken)
{
this._jWTAuthManager.TokenExpired += this._cacheManager.OnTokenExpired;
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
this._jWTAuthManager.TokenExpired -= this._cacheManager.OnTokenExpired;
return Task.CompletedTask;
}
}
并在启动中注册此服务:
services.AddHostedService<MyHostedService>();