|
小议优化ASP.NET应用性能之Cache篇(6) 2{ 3 string cacheKey = string.Format("NewsSetTopN-LG:{0}:CC:{1}:TN:{2}:OB:{3}:SO:{4}", language,classCode,topN.ToString(), orderBy.ToString(),sortOrder.ToString()); 4 5 //从上下文中读缓存项 6 RecordSet newsSet = HttpContext.Current.Items[cacheKey] as RecordSet; 7 if (newsSet == null) 8 { 9 //从HttpRuntime.Cache读缓存项 10 newsSet = SiteCache.Get(cacheKey) as RecordSet; 11 if (newsSet == null) 12 { 13 //直接从数据库从读取 14 CommonDataProvider dp=CommonDataProvider.Instance(); 15 newsSet =dp.GetNewsSetTopN(language,classCode,topN,orderBy,sortOrder); 16 //并将结果缓存到HttpRuntime.Cache中 17 SiteCache.Insert(cacheKey, newsSet, 60, CacheItemPriority.Normal); 18 } 19 20 } 21return newsSet; 22}
这样在5分钟内就不用重复访问数据库了来读该列表了,当然,也有人会问,如果在这5分钟内某条新闻删除了或修改了怎么办,没关系,我们在删除或修改时可以根据Cache KEY来强制删除该Cache项,当然,如果你觉得你对列表的时效性不是特别在意,你可以不强制删除该Cache项,让Cache项定义的时间点自动失效。当然,最好还是提供一个方法按匹配模式项来强行删除Cache项就可以了,例如:
1/**//// <summary> 2/// 删除匹配的NewsSetTopN列表的Cache项 3/// </summary> 4public static void ClearNewsSetTopNCache(string language,string classCode,int topN) 5{ 6 string cacheKey = string.Format("NewsSetTopN-LG:{0}:CC:{1}:TN:{2}",language,classCode,topN.ToString()); 7 SiteCache.RemoveByPattern(cacheKey); 8} 9
发布新闻后调用静态方法ClearNewsSetTopNCache()强行清除原来的TopN缓存项,例如:
1/**//// <summary> 2/// 发布(新建)新闻 3/// </summary> 4/// <param name="post">新闻实例</param> 5/// <returns>返回状态</returns> 6public static int Create(News post) 7{ 8 int status; 9 CommonDataProvider dp=CommonDataProvider.Instance(); 10 dp.CreateUpdateDeleteNews(post, DataAction.Create, out status);
|