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

 缓存用起来也就是通过Key来增删改查,内存缓存还可以在config中的配置对内存的使用情况

/// <summary>
/// 从内存缓存中读取配置。若缓存中不存在,则重新从文件中读取配置,存入缓存
/// </summary>
/// <param name="cacheKey">缓存Key</param>
/// <returns>配置词典</returns>
private static Dictionary<string, string> GetConfigDictionary(string cacheKey)
{
    Dictionary<string, string> configs = null;

    //1、获取内存缓存对象
    ObjectCache cache = MemoryCache.Default;
    
    //2、通过Key判断缓存中是否已有词典内容(Key在存入缓存时设置)
    if (cache.Contains(cacheKey))
    {
        //3、直接从缓存中读取词典内容
        configs = cache.GetCacheItem(cacheKey).Value as Dictionary<string, string>;
    }
    else
    {
        //3、读取配置文件,组成词典对象,准备放到缓存中
        configs = GetFromXml();
        
        //4、检查是否读取到配置内容
        if (configs != null)
        {
            //4、新建一个CacheItemPolicy对象,该对象用于声明配置对象在缓存中的处理策略
            CacheItemPolicy policy = new CacheItemPolicy();
            
            //5、因为配置文件一直需要读取,所以在此设置缓存优先级为不应删除
            // 实际情况请酌情考虑,同时可以设置AbsoluteExpiration属性指定过期时间
            policy.Priority = CacheItemPriority.NotRemovable;

            //6、将词典内容添加到缓存,传入 缓存Key、配置对象、对象策略
            // Set方法首先会检查Key是否在缓存中存在,如果存在,更新value,不存在则创建新的
            // 这里先加入缓存再加监视的原因是:在缓存加入时,也会触发监视事件,会导致出错。
            cache.Set(cacheKey, configs, policy);

            //7、监视文件需要传入一个IList对象,所以即便只有一个文件也需要新建List对象
            List<string> filePaths = new List<string>() { "c:\config.xml" };

            //8、新建一个文件监视器对象,添加对资源文件的监视
            HostFileChangeMonitor monitor = new HostFileChangeMonitor(filePaths);
            
            //9、调用监视器的NotifyOnChanged方法传入发生改变时的回调方法
            monitor.NotifyOnChanged(new OnChangedCallback((o) =>
                    { 
                        cache.Remove(cacheKey);
                    }
                ));
                
            //10、为配置对象的缓存策略加入监视器
            policy.ChangeMonitors.Add(monitor);
        }
    }
    return configs;
}
View Code

 

posted @ 2018-05-25 17:32  bxzjzg  阅读(419)  评论(0编辑  收藏  举报