亨利.王

通用的webCache

    public static class WebCache
    {
        /// <summary>
        /// 一般配置Cache过期时间,秒钟计
        /// </summary>
        /// <value>The common cache time out.</value>
        public static int CommonCacheTimeOut
        {
            get
            {
                if (_CommonCacheTimeOut == null)
                {
                    string settings = ConfigurationManager.AppSettings["CommonCacheTimeOut"];
                    int timeOut;
                    if (!int.TryParse(settings, out timeOut))
                        timeOut = 10;   //默认10分钟过期
                    _CommonCacheTimeOut = timeOut;
                }

                return _CommonCacheTimeOut.Value;
            }
        }
        private static int? _CommonCacheTimeOut;

        /// <summary>
        /// 查询配置Chche过期时间,秒钟计
        /// </summary>
        /// <value>The query cache time out.</value>
        public static int QueryCacheTimeOut
        {
            get
            {
                if (_QueryCacheTimeOut == null)
                {
                    string settings = ConfigurationManager.AppSettings["QueryCacheTimeOut"];
                    int timeOut;
                    if (!int.TryParse(settings, out timeOut))
                        timeOut = 10;   //默认10秒钟过期
                    _QueryCacheTimeOut = timeOut;
                }

                return _QueryCacheTimeOut.Value;
            }
        }
        private static int? _QueryCacheTimeOut;

        /// <summary>
        /// Cache插入锁
        /// </summary>
        private static object CacheLocker = new object();

        /// <summary>
        /// 获取缓存的对象。当没有缓存的时候,自动创建对象并进行缓存。只支持引用类型的缓存。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The key.</param>
        /// <param name="timeOut">单位:秒</param>
        /// <param name="onCreateInstance">The on create instance.</param>
        /// <returns></returns>
        public static T GetCachedObject<T>(string key, int timeOut, Func<T> onCreateInstance)
        {
            if (timeOut > 0)
            {
                //当前Cache对象
                System.Web.Caching.Cache webCache = System.Web.HttpRuntime.Cache;

                //获取缓存的对象
                T cachedObject = (T)webCache.Get(key);

                if (null == cachedObject)
                {
                    //加锁确保多线程安全
                    lock (CacheLocker)
                    {
                        cachedObject = (T)webCache.Get(key);
                        if (null == cachedObject)
                        {
                            //创建新的对象
                            cachedObject = onCreateInstance();
                            //将创建的对象进行缓存
                            if (cachedObject != null)
                                webCache.Insert(key, cachedObject, null, DateTime.Now.AddSeconds(timeOut), System.Web.Caching.Cache.NoSlidingExpiration);
                        }
                    }
                }
                return cachedObject;
            }
            else
            {
                //不设置缓存,则创建新的对象
                return onCreateInstance();
            }
        }

        /// <summary>
        /// 获取缓存的对象。当没有缓存的时候,自动创建对象并进行缓存。只支持引用类型的缓存。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The key.</param>
        /// <param name="onCreateInstance">The on create instance.</param>
        /// <returns></returns>
        public static T GetCachedObject<T>(string key, Func<T> onCreateInstance)
        {
            return GetCachedObject<T>(key, CommonCacheTimeOut, onCreateInstance);
        }

        /// <summary>
        /// 获取缓存的查询。当没有缓存的时候,自动创建对象并进行缓存。只支持引用类型的缓存。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The key.</param>
        /// <param name="onCreateInstance">The on create instance.</param>
        /// <returns></returns>
        public static T GetCachedQuery<T>(string key, Func<T> onCreateInstance)
        {
            return GetCachedObject<T>(key, QueryCacheTimeOut, onCreateInstance);
        }

        /// <summary>
        /// 移除缓存的对象
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public static object Remove(string key)
        {
            //当前Cache对象
            System.Web.Caching.Cache webCache = System.Web.HttpRuntime.Cache;

            lock (CacheLocker)
            {
                return webCache.Remove(key);
            }
        }

        /// <summary>
        /// 清除所有缓存
        /// </summary>
        public static void RemoveAll()
        {          
           
            IDictionaryEnumerator cacheEnum = System.Web.HttpRuntime.Cache.GetEnumerator();
            while (cacheEnum.MoveNext())
            {
                System.Web.HttpRuntime.Cache.Remove(cacheEnum.Key.ToString());
            }
        }
    }

 

 

如何调用呢?

        /// <summary>
        /// 获取新闻内容
        /// </summary>
        /// <param name="articleID"></param>
        /// <param name="token"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static ArticleInfoEntity GetCachedArticleInfo(long articleID, string token, int mode)
        {
            string key = "GetArticleInfo_" + articleID;
            return
                WebCache.GetCachedObject<ArticleInfoEntity>(key, InterfaceHelper.ContentCacheTime,
                delegate()
                {
                    ArticleInfoEntity articleInfo;
                    int iUseXml = ConfigurationManager.AppSettings["UseStaticContent"] != null ? Convert.ToInt32(ConfigurationManager.AppSettings["UseStaticContent"]) : 0;
                   
                    if ( 1 == iUseXml ) //直接读xml
                    {
                        articleInfo = GetArticleInfoByFile(articleID);
                    }
                    else //尝试先读数据库
                    {
                        //DB Error
                        if (InterfaceHelper.CheckDBError())
                        {
                            articleInfo = GetArticleInfoByFile(articleID);
                        }
                        else
                        {
                            try
                            {
                                articleInfo = GetArticleInfo(articleID, token, mode);
                                //DB OK
                                InterfaceHelper.SetDBTrue();
                            }
                            //DB Error
                            catch (SqlException ex)
                            {
                                InterfaceHelper.SetDBError();
                                articleInfo = GetArticleInfoByFile(articleID);
                                ExceptionHandler.Instance.HandleExceptionEx(ex);
                            }
                        }
                    }
                   
                    return articleInfo;
                });
        }

posted on 2011-10-11 10:31  亨利.王  阅读(...)  评论(...编辑  收藏

导航

统计