NetCore的缓存使用详例 (2)

满足任意一个缓存都将失效

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也失效

/// <summary> /// 缓存依赖策略 /// </summary> public void CacheDependencyPolicy() { string DependentCTS = "DependentCTS"; string cacheKeyParent = "CacheKeys.Parent"; string cacheKeyChild = "CacheKeys.Child"; var cts = new CancellationTokenSource(); _memoryCache.Set(DependentCTS, cts); //创建一个cache策略 using (var entry = _memoryCache.CreateEntry(cacheKeyParent)) { //当前key对应的值 entry.Value = "parent" + DateTime.Now; //当前key对应的回调事件 entry.RegisterPostEvictionCallback(MyCallback, this); //基于些key创建一个依赖缓存 _memoryCache.Set(cacheKeyChild, "child" + DateTime.Now, new CancellationChangeToken(cts.Token)); } string ParentCachedTime = _memoryCache.Get<string>(cacheKeyParent); string ChildCachedTime = _memoryCache.Get<string>(cacheKeyChild); string callBackMsg = _memoryCache.Get<string>("callbackMessage"); Console.WriteLine("第一次获取"); Console.WriteLine(ParentCachedTime + "|" + ChildCachedTime + "|" + callBackMsg); //移除parentKey _memoryCache.Get<CancellationTokenSource>(DependentCTS).Cancel(); Thread.Sleep(1000); ParentCachedTime = _memoryCache.Get<string>(cacheKeyParent); ChildCachedTime = _memoryCache.Get<string>(cacheKeyChild); callBackMsg = _memoryCache.Get<string>("callbackMessage"); Console.WriteLine("第二次获取"); Console.WriteLine(ParentCachedTime + "|" + ChildCachedTime + "|" + callBackMsg); } 参考资料

.NetCore缓存篇之MemoryCache

Asp.Net Core 轻松学-在.Net Core 使用缓存和配置依赖策略

拥抱.NET Core系列:MemoryCache 缓存过期

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpzxxp.html