自从
IMemoryCache
不会提供太多有关缓存项的信息,我正考虑实现一些自定义项,以便在缓存中保留有关项的数据,如
key
,
AbsoluteExpiration
财产等。
这是我的实现
伊梅莫里奇
:
public class MemoryCacheService : IMemoryCache
{
private readonly MemoryCache _memoryCache;
private readonly List<CacheItemRelevantData> _allKeys;
private readonly string AllKeys = "___All__Keys___";
public MemoryCacheService()
{
_memoryCache = new MemoryCache(new MemoryCacheOptions());
_allKeys = new List<CacheItemRelevantData>();
_memoryCache.Set(AllKeys, _allKeys, new MemoryCacheEntryOptions
{
AbsoluteExpiration = DateTimeOffset.MaxValue
});
}
public void Dispose()
{
_memoryCache.Dispose();
}
public bool TryGetValue(object key, out object value)
{
return _memoryCache.TryGetValue(key, out value);
}
public ICacheEntry CreateEntry(object key)
{
var entry = _memoryCache.CreateEntry(key);
entry.RegisterPostEvictionCallback((o, v, reason, state) =>
{
if (reason.In(EvictionReason.Capacity, EvictionReason.Expired, EvictionReason.TokenExpired))
{
var item = _allKeys.FirstOrDefault(x => x.Key.ToString() == o.ToString());
if (item != null)
{
_allKeys.Remove(item);
}
}
});
if (!_allKeys.Select(x => x.Key).Contains(key))
{
_allKeys.Add(new CacheItemRelevantData
{
Key = entry.Key,
AbsoluteExpiration = entry.AbsoluteExpiration,
Priority = entry.Priority,
AbsoluteExpirationRelativeToNow = entry.AbsoluteExpirationRelativeToNow,
Size = entry.Size
});
}
return entry;
}
public void Remove(object key)
{
var entry = _allKeys.FirstOrDefault(x => x.Key.ToString() == key.ToString());
if (entry != null)
{
_allKeys.Remove(entry);
}
_memoryCache.Remove(key);
}
}
但是自从
_allKeys
是为了存储缓存项的相关数据而创建的,我不希望它过期。
有没有办法将“过期时间”设置为“无”或类似的值
_所有键
列表将永远保存在缓存中?