码迷,mamicode.com
首页 > 系统相关 > 详细

MemoryCache缓存 ---缓存时效

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

标签:mon   图片   addm   dmi   close   turn   else   policy   tostring   

 

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缓存 ---缓存时效

标签:mon   图片   addm   dmi   close   turn   else   policy   tostring   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!