C#Cache缓存的封装类

  c#自带的缓存Cache是将缓存数据写在内存里面的,读取速度还是相当快的,也比较安全,由于是写在内存里面,一旦回收iis,Cache里面的缓存也会丢失。

  public class CacheHelper
    {
        ///


        /// 创建缓存项的文件
        ///

        /// 缓存Key
        /// object对象
        public static void Insert(string key, object obj)
        {
            //创建缓存
            HttpContext.Current.Cache.Insert(key, obj);
        }
        ///
        /// 移除缓存项的文件
        ///

        /// 缓存Key
        public static void Remove(string key)
        {
            //创建缓存
            HttpContext.Current.Cache.Remove(key);
        }
        ///
        /// 创建缓存项的文件依赖
        ///

        /// 缓存Key
        /// object对象
        /// 文件绝对路径
        public static void Insert(string key, object obj, string fileName)
        {
            //创建缓存依赖项
            CacheDependency dep = new CacheDependency(fileName);
            //创建缓存
            HttpContext.Current.Cache.Insert(key, obj, dep);
        }

        ///


        /// 创建缓存项过期
        ///

        /// 缓存Key
        /// object对象
        /// 过期时间(分钟)
        public static void Insert(string key, object obj, int expires)
        {
            HttpContext.Current.Cache.Insert(key, obj, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, expires, 0));
        }

        ///


        /// 获取缓存对象
        ///

        /// 缓存Key
        /// object对象
        public static object Get(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return null;
            }
            return HttpContext.Current.Cache.Get(key);
        }

        ///


        /// 获取缓存对象
        ///

        /// T对象
        /// 缓存Key
        ///
        public static T Get(string key)
        {
            object obj = Get(key);
            return obj == null ? default(T) : (T)obj;
        }
        ///
        /// 获取有所缓存key
        ///

        public static List GetKeyAll()
        {
            List cacheKeys = new List();
            var cacheEnum = HttpContext.Current.Cache.GetEnumerator();
            while (cacheEnum.MoveNext())
            {
                cacheKeys.Add(cacheEnum.Key.ToString());
            }
            return cacheKeys;
        }
    }

你可能感兴趣的:(c#)