首页 > 系统服务 > 详细

MemoryCache缓存 ---缓存时效

时间:2018-05-25 17:47:18      阅读:235      评论:0      收藏:0      [点我收藏+]

 

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;
        }
    }
View Code

 

MemoryCache缓存 ---缓存时效

原文:https://www.cnblogs.com/love201314/p/9089905.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!