如何正确清除ASP.NET内核中的IMemoryCache?
我相信这个类缺少清晰的方法,但无论如何如何处理它呢?在我的项目中,我对DocumentRepository的方法进行了24小时的缓存,从数据库中获得了很多行。但有时我可以更改数据库,所以我想清除IMemoryCache,因为它有垃圾数据。
发布于 2021-02-11 06:56:41
IMemoryCache
确实缺少Clear()
方法,但是自己实现一个并不难。
public class CacheWrapper
{
private readonly IMemoryCache _memoryCache;
private CancellationTokenSource _resetCacheToken = new();
public CacheWrapper(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public void Add(object key, object value, MemoryCacheEntryOptions memoryCacheEntryOptions)
{
using var entry = _memoryCache.CreateEntry(key);
entry.SetOptions(memoryCacheEntryOptions);
entry.Value = value;
// add an expiration token that allows us to clear the entire cache with a single method call
entry.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));
}
public void Clear()
{
_resetCacheToken.Cancel(); // this triggers the CancellationChangeToken to expire every item from cache
_resetCacheToken.Dispose(); // dispose the current cancellation token source and create a new one
_resetCacheToken = new CancellationTokenSource();
}
}
基于https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-3.1#cache-dependencies和https://stackoverflow.com/a/45543023/2078975
发布于 2019-05-27 02:14:29
缓存类和接口没有任何方法来清除它们来迭代键,因为它不意味着是一个列表,并且在ASP.NET核心应用程序中通常使用IDistributedCache
接口作为依赖项,因为它更容易让您稍后从本地内存缓存更改为分布式缓存(如memd或Redis)。
相反,如果要使特定行无效,则应通过cache.Remove(myKey)
删除缓存的条目。
当然,这需要您知道要使其无效的密钥。通常,您可以通过事件来实现这一点。每次更新数据库中的条目时,都会触发一个事件。此事件将被后台服务捕获并导致缓存无效。
在本地,这可以通过任何pub/sub库来完成。在分布式场景中,您可能希望使用分布式缓存(即Redis)的发布/订阅功能。
在查找表的情况下(其中很多值都会受到影响),您可以让服务刷新缓存(即每隔5到10分钟通过使用诸如hangfire或quart.net的调度库的后台任务)。
家庭作业问题
但是您应该问自己一个问题:如果文档频繁更改,那么将文档缓存24小时真的是一个好主意吗?
加载单个文档是否花费了如此多的时间,以至于24小时缓存它是值得的?或者更短的时间(15分钟、30分钟、60分钟)就足够了?
发布于 2019-11-12 11:25:07
要清除你的MemoryCache,只需按键移除内存缓存,如下所示:
memoryCache.Remove("your_key");
https://stackoverflow.com/questions/56315930
复制相似问题