先说下当前项目的场景:
后台人员1天不定时的,添加新闻和视频图片10条左右,数量不多
不使用缓存,回和数据库打交道,非常耗时,造成效率低,尤其是在数据量非常庞大的情况下
可是加了缓存,加多少时间的缓存?新闻要保证实时更新,一发布立刻显示出来
微软给出了解决方法,数据库缓存依赖项,但是貌似只能用在SQL上,而且要配置些东西;还有,并不透明~ 一些东西看不到。这里提供另一种方法:
先说下大概思路,在所有查找操作时,都把结果插入 cache 在对数据库有操作时(增删改) 删除cache
有了思路,开始解决问题,这里会遇到两个问题
第一 : 所有查找时,cache建怎么定义,保证不重复呢
第二:微软没有提供删除所有cache的方法,只有cache["键值名"].Remove(); 而没有removeall();
下面上代码和解决办法 以及思路
- #region##根据条件得到新闻
-
-
-
-
-
-
-
- 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);
- }
- }
|