关于IMemoryCache的GetOrCreate方法缺失MemoryCacheEntryOptions支持的问询
关于IMemoryCache扩展方法的疑问探讨
最近在研究IMemoryCache的实现,先给大家梳理下当前这个接口的核心方法,它包含三个基础成员:
bool TryGetValue(object key, out object value); ICacheEntry CreateEntry(object key); void Remove(object key);
日常开发中,我们常用两种方式查询缓存条目:
- 第一种是借助
Get方法做判断:
// first way if (string.IsNullOrEmpty(cache.Get<string>("timestamp"))) { cache.Set<string>("timestamp", DateTime.Now.ToString()); }
- 第二种是用
TryGetValue做更严谨的存在性校验:
// second way if (!cache.TryGetValue<string>("timestamp", out string timestamp)) { // cache.Set<string>("timestamp", DateTime.Now.ToString()); }
除此之外,还有一个GetOrCreate扩展方法,它的设计逻辑是当缓存不存在时,通过传入的工厂方法创建新的缓存条目,现有实现代码如下:
public static TItem GetOrCreate<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, TItem> factory) { object obj; if (!cache.TryGetValue(key, out obj)) { ICacheEntry entry = cache.CreateEntry(key); obj = (object)factory(entry); entry.SetValue(obj); entry.Dispose(); } return (TItem)obj; }
这里我发现了一个问题:我们知道Set方法支持传入MemoryCacheEntryOptions,或者直接指定absoluteExpirationRelativeToNow、absoluteExpiration这类参数来配置缓存的过期策略,但现有的GetOrCreate方法在创建新条目时,并没有提供这类条目级过期配置的入口。
我想确认一下,是不是我遗漏了什么,其实已经有支持该功能的重载方法了?还是说确实需要提交PR来补充相关的扩展方法,让GetOrCreate也能支持自定义过期配置?
另外附上用到的辅助扩展方法代码:
public static ICacheEntry SetValue(this ICacheEntry entry, object value) { entry.Value = value; return entry; }
我已经在项目相关仓库提交了Issue来寻求官方反馈。
内容的提问来源于stack exchange,提问作者Razvan Dumitru
相关产品推荐
相关产品推荐

