MemoryCache缓存 ---缓存时效
Posted bxzjzg
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MemoryCache缓存 ---缓存时效相关的知识,希望对你有一定的参考价值。
MemoryCache缓存 ---缓存时效测试
var cachePool = new MyCachePool();
//Thread.Sleep(1000);
var value = cachePool.GetFileValue();
/// <summary> /// MemoryCache缓存 /// </summary> public class MyCachePool { ObjectCache cache = MemoryCache.Default; const string cacheKey = "TestCacheKey"; public string GetValue() { var content = cache[cacheKey] as string; if (content == null) { //Console.WriteLine("Get New Item"); var policy = new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.AddSeconds(5) }; content = Guid.NewGuid().ToString(); cache.Set(cacheKey, content, policy); } else { Console.WriteLine("Get cached item"); } return content; } public string GetFileValue() { string strCacheKey = "FileCacheKey"; var content = cache[strCacheKey] as string; if (content == null) { //Console.WriteLine("Get New Item"); //var file = @"E:\test.txt"; //CacheItemPolicy policy = new CacheItemPolicy(); //policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string> { file })); //content = File.ReadAllText(file); //cache.Set(strCacheKey, content, policy); CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(3); content = Guid.NewGuid().ToString(); CacheItem item = new CacheItem("cachedText", content); List<string> keys = new List<string> { strCacheKeyChange }; policy.ChangeMonitors.Add(cache.CreateCacheEntryChangeMonitor(keys)); //依赖某个值变化 cache.Set(item, policy); } else { Console.WriteLine("Get cached item"); } return content; } }
以上是关于MemoryCache缓存 ---缓存时效的主要内容,如果未能解决你的问题,请参考以下文章