Mak*_*kla 3 .net-core asp.net-core
乍一看,这似乎是该问题的重复,但是我没有问如何清除EF的缓存。
如何清除IMemoryCache接口设置的整个缓存?
public CacheService(IMemoryCache memoryCache)
{
this._memoryCache = memoryCache;
}
public async Task<List<string>> GetCacheItem()
{
if (!this._memoryCache.TryGetValue("Something", out List<string> list))
{
list= await this ...
this._memoryCache.Set("Something", list, new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove));
}
return list;
}
Run Code Online (Sandbox Code Playgroud)
这只是一个例子。我有许多类/方法正在存储要缓存的值。现在,我需要将其全部删除。
在某些情况下,我的密钥是动态创建的,因此我不知道需要删除哪些密钥。清除将是完美的。
我可以编写自己的接口和类以供内部使用IMemoryCache,但这似乎有些过分。有没有更简单的选择?
一键处理和删除不是一个好主意,故障点太多。我在生产和单元测试中使用过这段代码,效果很好。我还没有找到一个很好的答案来解释为什么 IMemoryCache 缺少 Clear 方法。如果你有一个Compact方法,你可以通过 1.0,即Compact(1.0)清除,但如果没有,这段代码应该适用于 .NET core 2.2:
PropertyInfo prop = cache.GetType().GetProperty("EntriesCollection", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Public);
object innerCache = prop.GetValue(cache);
MethodInfo clearMethod = innerCache.GetType().GetMethod("Clear", BindingFlags.Instance | BindingFlags.Public);
clearMethod.Invoke(innerCache, null);
Run Code Online (Sandbox Code Playgroud)
因为找不到任何好的解决方案,所以我编写了自己的解决方案。
在SamiAl90解决方案(答案)中,我错过了ICacheEntry界面的所有属性。
在内部,它使用IMemoryCache。
用例与2个其他功能完全相同:
您必须注册单身人士:
serviceCollection.AddSingleton<IMyCache, MyMemoryCache>();
Run Code Online (Sandbox Code Playgroud)
用例:
public MyController(IMyCache cache)
{
this._cache = cache;
}
[HttpPut]
public IActionResult ClearCache()
{
this._cache.Clear();
return new JsonResult(true);
}
[HttpGet]
public IActionResult ListCache()
{
var result = this._cache.Select(t => new
{
Key = t.Key,
Value = t.Value
}).ToArray();
return new JsonResult(result);
}
Run Code Online (Sandbox Code Playgroud)
资源:
public interface IMyCache : IEnumerable<KeyValuePair<object, object>>, IMemoryCache
{
/// <summary>
/// Clears all cache entries.
/// </summary>
void Clear();
}
public class MyMemoryCache : IMyCache
{
private readonly IMemoryCache _memoryCache;
private readonly ConcurrentDictionary<object, ICacheEntry> _cacheEntries = new ConcurrentDictionary<object, ICacheEntry>();
public MyMemoryCache(IMemoryCache memoryCache)
{
this._memoryCache = memoryCache;
}
public void Dispose()
{
this._memoryCache.Dispose();
}
private void PostEvictionCallback(object key, object value, EvictionReason reason, object state)
{
if (reason != EvictionReason.Replaced)
this._cacheEntries.TryRemove(key, out var _);
}
/// <inheritdoc cref="IMemoryCache.TryGetValue"/>
public bool TryGetValue(object key, out object value)
{
return this._memoryCache.TryGetValue(key, out value);
}
/// <summary>
/// Create or overwrite an entry in the cache and add key to Dictionary.
/// </summary>
/// <param name="key">An object identifying the entry.</param>
/// <returns>The newly created <see cref="T:Microsoft.Extensions.Caching.Memory.ICacheEntry" /> instance.</returns>
public ICacheEntry CreateEntry(object key)
{
var entry = this._memoryCache.CreateEntry(key);
entry.RegisterPostEvictionCallback(this.PostEvictionCallback);
this._cacheEntries.AddOrUpdate(key, entry, (o, cacheEntry) =>
{
cacheEntry.Value = entry;
return cacheEntry;
});
return entry;
}
/// <inheritdoc cref="IMemoryCache.Remove"/>
public void Remove(object key)
{
this._memoryCache.Remove(key);
}
/// <inheritdoc cref="IMyCache.Clear"/>
public void Clear()
{
foreach (var cacheEntry in this._cacheEntries.Keys.ToList())
this._memoryCache.Remove(cacheEntry);
}
public IEnumerator<KeyValuePair<object, object>> GetEnumerator()
{
return this._cacheEntries.Select(pair => new KeyValuePair<object, object>(pair.Key, pair.Value.Value)).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Gets keys of all items in MemoryCache.
/// </summary>
public IEnumerator<object> Keys => this._cacheEntries.Keys.GetEnumerator();
}
public static class MyMemoryCacheExtensions
{
public static T Set<T>(this IMyCache cache, object key, T value)
{
var entry = cache.CreateEntry(key);
entry.Value = value;
entry.Dispose();
return value;
}
public static T Set<T>(this IMyCache cache, object key, T value, CacheItemPriority priority)
{
var entry = cache.CreateEntry(key);
entry.Priority = priority;
entry.Value = value;
entry.Dispose();
return value;
}
public static T Set<T>(this IMyCache cache, object key, T value, DateTimeOffset absoluteExpiration)
{
var entry = cache.CreateEntry(key);
entry.AbsoluteExpiration = absoluteExpiration;
entry.Value = value;
entry.Dispose();
return value;
}
public static T Set<T>(this IMyCache cache, object key, T value, TimeSpan absoluteExpirationRelativeToNow)
{
var entry = cache.CreateEntry(key);
entry.AbsoluteExpirationRelativeToNow = absoluteExpirationRelativeToNow;
entry.Value = value;
entry.Dispose();
return value;
}
public static T Set<T>(this IMyCache cache, object key, T value, MemoryCacheEntryOptions options)
{
using (var entry = cache.CreateEntry(key))
{
if (options != null)
entry.SetOptions(options);
entry.Value = value;
}
return value;
}
public static TItem GetOrCreate<TItem>(this IMyCache cache, object key, Func<ICacheEntry, TItem> factory)
{
if (!cache.TryGetValue(key, out var result))
{
var entry = cache.CreateEntry(key);
result = factory(entry);
entry.SetValue(result);
entry.Dispose();
}
return (TItem)result;
}
public static async Task<TItem> GetOrCreateAsync<TItem>(this IMyCache cache, object key, Func<ICacheEntry, Task<TItem>> factory)
{
if (!cache.TryGetValue(key, out object result))
{
var entry = cache.CreateEntry(key);
result = await factory(entry);
entry.SetValue(result);
entry.Dispose();
}
return (TItem)result;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4586 次 |
| 最近记录: |