代码之家  ›  专栏  ›  技术社区  ›  Rey

在IMemoryCache实现中不要使缓存项过期

  •  1
  • Rey  · 技术社区  · 7 年前

    自从 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 是为了存储缓存项的相关数据而创建的,我不希望它过期。

    有没有办法将“过期时间”设置为“无”或类似的值 _所有键 列表将永远保存在缓存中?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Rey    7 年前

    对我来说,我可以很容易地解决这个问题,因为 IMemoryService 被配置为作用域服务,这意味着 _allKeys 变量一直保存在内存中 IMemoryService公司 实例(直到重新启动iis或其他操作)。对于非作用域服务,我没有找到合适的解决方案,但我认为 IMemoryCache 服务应该始终是一个作用域服务(没有实际情况需要对其进行不同的配置- 也许 吧!! )