先说下当前项目的场景:
后台人员1天不定时的,添加新闻和视频图片10条左右,数量不多
不使用缓存,回和数据库打交道,非常耗时,造成效率低,尤其是在数据量非常庞大的情况下
可是加了缓存,加多少时间的缓存?新闻要保证实时更新,一发布立刻显示出来
微软给出了解决方法,数据库缓存依赖项,但是貌似只能用在SQL上,而且要配置些东西;
还有,并不透明~ 一些东西看不到
这里提供另一种方法:
先说下大概思路,在所有查找操作时,都把结果插入 cache 在对数据库有操作时(增删改) 删除cache
有了思路,开始解决问题,这里会遇到两个问题
*** : 所有查找时,cache建怎么定义,保证不重复呢
第二:微软没有提供删除所有cache的方法,只有cache["键值名"].Remove(); 而没有removeall();
下面上代码和解决办法 以及思路
- #region##根据条件得到新闻
- /// <summary>
- /// 根据条件得到新闻
- /// </summary>
- /// <param name="tableName"></param>
- /// <param name="whereStr"></param>
- /// <param name="topCount"></param>
- /// <returns></returns>
- public List<CmsDemoModels.NewsInfo> GetByCondition(string whereStr, string topCount)
- {
- string cacheKey = string.Format("{0}.{1}.{2}", GetType(), "GetByCondition",whereStr+topCount);
- if (HttpRuntime.Cache[cacheKey] != null)
- {
- return HttpRuntime.Cache[cacheKey] as List<CmsDemoModels.NewsInfo>;
- }
- else
- {
- //从数据库里查找并插入缓存
- using (CmsDemoDAL.NewsInfoServcie ns = new NewsInfoServcie())
- {
- List<NewsInfo> newsList=ns.GetByCondition(whereStr, topCount);
- HttpRuntime.Cache.Insert(cacheKey,newsList, null, DateTime.Now.AddDays(1), TimeSpan.Zero);
- return newsList;
- }
- }
- }
看上面的代码
- string cacheKey = string.Format("{0}.{1}.{2}", GetType(), "GetByCondition",whereStr+topCount);
我定义这缓存键值不重复的方法是,用当前类+方法名+所有参数名的组合,来保证***性这样把所有查询的方法 以及查询结果都缓存起来了~
- public static void ClearOutputCache()
- {
- //移除自定义缓存
- foreach (var item in HttpRuntime.Cache.Cast<DictionaryEntry>().ToArray())
- {
- HttpRuntime.Cache.Remove((string)item.Key);
- }
- }
上面的方法,是删除所有缓存
可是又有个问题,我们有视频表、图片表、新闻等等,我现在更新个新闻,就要删除所有的缓存,其实只用删除所有新闻的缓存就行了
- #region 删除缓存
- /// <summary>
- /// 根据名字开头删除缓存
- /// </summary>
- /// <param name="StartName">缓存名字开头</param>
- public void RemoveAllCache(string StartName)
- {
- //移除自定义应用程序缓存
- DictionaryEntry[] de = HttpRuntime.Cache.Cast<DictionaryEntry>().ToArray();
- foreach (var item in de)
- {
- string cacheKey = item.Key.ToString();
- if (cacheKey.StartsWith(StartName))
- {
- HttpRuntime.Cache.Remove((string)item.Key);
- }
- }
- }
- #endregion
稍微改进下 效率又大大的提高了
当我们数据库有变化时,比如添加了个新闻调用
- p.RemoveAllCache(GetType().ToString());
- #region##添加新闻
- /// <summary>
- /// 添加新闻
- /// </summary>
- /// <param name="info"></param>
- /// <returns></returns>
- public int Add(CmsDemoModels.NewsInfo info)
- {
- using (CmsDemoDAL.NewsInfoServcie ns = new NewsInfoServcie())
- {
- info.ViewCount = 0;
- info.State = 0;
- info.SortIndex = GetMaxSort() + 1;
- int i= ns.Add(info);
- PubClass p = new PubClass();
- p.RemoveAllCache(GetType().ToString());
- return i;
- }
- }
- #endregion
这样就把所有以GetType().ToString() 开头的删除掉了~~ 实现新闻的删除新闻的,视频的删除视频的
PS: 这里新闻添加和查找都是在BLL层下的NewInfoManager类下,所以他们的 GetType().ToString() 会一样大概思路就这样
有什么问题,可以留言交流,欢迎讨论~
原文链接:http://www.cnblogs.com/wlflovenet/archive/2011/06/30/Cache.html
【编辑推荐】