满足任意一个缓存都将失效
string cacheCombineKey = "combineKey"; MemoryCacheEntryOptions combineOptions = new MemoryCacheEntryOptions(); combineOptions.SlidingExpiration = TimeSpan.FromSeconds(2); combineOptions.AbsoluteExpiration = DateTime.Now.AddSeconds(6); _memoryCache.Set(cacheCombineKey, DateTime.Now.ToString(), combineOptions); //get slibing cache for (int i = 0; i < 2; i++) { Console.WriteLine(_memoryCache.Get(cacheCombineKey)); Thread.Sleep(1000); } for (int i = 0; i < 6; i++) { Thread.Sleep(2000); Console.WriteLine(i+"|" + _memoryCache.Get(cacheCombineKey)); } Console.WriteLine("------------combineKey End----------------"); 缓存状态变化事件当缓存更新、删除时触发一个回调事件,记录缓存变化的内容。
/// <summary> /// cache状态变化回调 /// </summary> public void CacheStateCallback() { MemoryCacheEntryOptions options = new MemoryCacheEntryOptions(); options.AbsoluteExpiration = DateTime.Now.AddSeconds(3 ); options.RegisterPostEvictionCallback(MyCallback, this); //show callback console string cacheKey = "absoluteKey"; _memoryCache.Set(cacheKey, DateTime.Now.ToString(), options); Thread.Sleep(500); _memoryCache.Set(cacheKey, DateTime.Now.ToString(), options); _memoryCache.Remove(cacheKey); } private static void MyCallback(object key, object value, EvictionReason reason, object state) { var message = $"Cache entry state change:{key} {value} {reason} {state}"; ((CacheService)state)._memoryCache.Set("callbackMessage", message); Console.WriteLine(message); } 缓存依赖策略设置一个缓存A
设置一个缓存B,依赖于缓存A 如果缓存A失效,缓存B也失效
.NetCore缓存篇之MemoryCache
Asp.Net Core 轻松学-在.Net Core 使用缓存和配置依赖策略
拥抱.NET Core系列:MemoryCache 缓存过期