【发布时间】:2020-06-03 05:15:34
【问题描述】:
这就是我实现 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;
}
}
我的调用顺序是:
- AddTokenToCache(令牌成功添加到缓存)
- GetAllToken(显示一个令牌被添加到缓存中)
- AddTokenToCache(令牌成功添加到缓存)
- GetAllToken(显示两个令牌都已添加到缓存中)
- 触发调用 RemoveFromCache 的 TokenExpired 事件(令牌为空)
- GetAllToken(显示两个令牌都已添加到缓存中)
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;
}
【问题讨论】:
-
1.我尝试了您的代码但无法重现,您是否正确注入了服务?您能否包括启动和调用 CacheManager 的代码? 2.有没有重现的demo?
-
确定..我正在添加 Startup.cs
-
是的,我在删除时从另一个点调用缓存服务......让我分享代码 - 是这个原因......那么替代方案是什么?
标签: asp.net-core caching memcached