博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

 1. 申明一个Cache

     private static Cache cache = HttpRuntime.Cache; 

2.  往Cache内插入值

  cache.Insert(CreateKey(category, key), value, null, Cache.NoAbsoluteExpiration, TimeSpan.Zero);

3 读取Cache类的值

   /// <summary>
        /// 获取缓存项
        /// </summary>
        /// <param name="category">缓存所属分类</param>
        /// <param name="key">键</param>
        /// <returns>缓存项</returns>
        public static object GetValue(string category, string key)
        {
            return cache[CreateKey(category, key)];
        }

  4 清除Cache内的值

 

  //全部清除Cache内的值

   if (cache.Count == 0)
            {
                //没有缓存项,直接返回
                return;
            }
            lock (cache)
            {
                List<string> list = new List<string>();
                var enumerator = cache.GetEnumerator();
                string key = null;
                while (enumerator.MoveNext())
                {
                    key = enumerator.Key.ToString();
                    list.Add(key);
                }
                list.ForEach(item => cache.Remove(item));
            }  

    

    //清除指定的Cache内的值

    lock (cache)
            {
                var enumerator = cache.GetEnumerator();
                List<string> list = new List<string>(cache.Count);
                string key = null;
                while (enumerator.MoveNext())
                {
                    key = enumerator.Key.ToString();
                    if (key.StartsWith(start))
                    {
                        //以所属分类作为开头的键符合清除条件
                        list.Add(key);
                    }
                }
                list.ForEach(item => cache.Remove(item));
            }