C#运用Cache缓存基础数据,防止多次读取数据库

1、首先是Cache帮助类

 public class CacheHelper
    {
        /// 
        /// 获取数据缓存
        /// 
        /// 键
        public static object GetCache(string cacheKey)
        {
            var objCache = HttpRuntime.Cache.Get(cacheKey);
            return objCache;
        }
        /// 
        /// 设置数据缓存
        /// 
        public static void SetCache(string cacheKey, object objObject)
        {
            var objCache = HttpRuntime.Cache;
            objCache.Insert(cacheKey, objObject);
        }
        /// 
        /// 设置数据缓存
        /// 
        public static void SetCache(string cacheKey, object objObject, int timeout = 24*60*60)
        {
            try
            {
                if (objObject == null) return;
                var objCache = HttpRuntime.Cache;
                //相对过期
                //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);
                //绝对过期时间
                objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null);
            }
            catch (Exception)
            {
                //throw;
            }
        }
        /// 
        /// 移除指定数据缓存
        /// 
        public static void RemoveAllCache(string cacheKey)
        {
            var cache = HttpRuntime.Cache;
            cache.Remove(cacheKey);
        }
        /// 
        /// 移除全部缓存
        /// 
        public static void RemoveAllCache()
        {
            var cache = HttpRuntime.Cache;
            var cacheEnum = cache.GetEnumerator();
            while (cacheEnum.MoveNext())
            {
                cache.Remove(cacheEnum.Key.ToString());
            }
        }

    }

2、实现部分代码

 public static class DictionaryHelper
 {
        /// 
        /// 获取所有的字典
        /// 
        /// 
        /// 
        public static Dictionary FindCommonDictionary(string DicName)
        {
            try
            {
                var cache = CacheHelper.GetCache("commonData_Dictionary");//先读取
                if (cache == null)//如果没有该缓存
                {
                    var queryCommon = service.GetS_DICTIONARY_COMMONs();//从数据库取出
                    CacheHelper.SetCache("commonData_Dictionary", queryCommon);//添加缓存
                    return queryCommon[DicName];  //根据字典名字取出对应的字典
                }
                var result = (Dictionary>)cache;//有就直接返回该缓存
                return result[DicName];//根据字典名字取出对应的字典
            }
            catch (Exception ex)
            {
                return null;         //没有该字典返回空
            }
           
        }
      }

3、当新增更新删除字典的时候要清除缓存中的数据,重新加载

 CacheHelper.RemoveAllCache("commonData_Dictionary");

你可能感兴趣的:(z,1)