技术开发 频道

小议优化ASP.NET应用性能之Cache篇

    其实该类主要就是利用前文所提及的关于Cache依赖项的第一点与第二点的特性来维护我们自己的Cache项。
    有了SiteCache类,接下来看看如何使用它。还是以读取新闻TonN列表为例:
public static RecordSet GetNewsSetTopN(string classCode,int topN,SortPostsBy orderBy, SortOrder sortOrder, string language) { string cacheKey = string.Format("NewsSetTopN-LG:{0}:CC:{1}:TN:{2}:OB:{3}:SO:{4}", language,classCode,topN.ToString(), orderBy.ToString(),sortOrder.ToString()); //从上下文中读缓存项 RecordSet newsSet = HttpContext.Current.Items[cacheKey] as RecordSet; if (newsSet == null) { //从HttpRuntime.Cache读缓存项 newsSet = SiteCache.Get(cacheKey) as RecordSet; if (newsSet == null) { //直接从数据库从读取 CommonDataProvider dp=CommonDataProvider.Instance(); newsSet =dp.GetNewsSetTopN(language,classCode,topN,orderBy,sortOrder); //并将结果缓存到HttpRuntime.Cache中 SiteCache.Insert(cacheKey, newsSet, 60, CacheItemPriority.Normal); } } return newsSet; }
    这样在5分钟内就不用重复访问数据库了来读该列表了,当然,也有人会问,如果在这5分钟内某条新闻删除了或修改了怎么办,没关系,我们在删除或修改时可以根据Cache KEY来强制删除该Cache项,当然,如果你觉得你对列表的时效性不是特别在意,你可以不强制删除该Cache项,让Cache项定义的时间点自动失效。当然,最好还是提供一个方法按匹配模式项来强行删除Cache项就可以了,例如:
/**//// <summary> /// 删除匹配的NewsSetTopN列表的Cache项 /// </summary> public static void ClearNewsSetTopNCache(string language,string classCode,int topN) { string cacheKey = string.Format("NewsSetTopN-LG:{0}:CC:{1}:TN:{2}",language,classCode,topN.ToString()); SiteCache.RemoveByPattern(cacheKey); }
    发布新闻后调用静态方法ClearNewsSetTopNCache()强行清除原来的TopN缓存项,例如:
/**//// <summary> /// 发布(新建)新闻 /// </summary> /// <param name="post">新闻实例</param> /// <returns>返回状态</returns> public static int Create(News post) { int status; CommonDataProvider dp=CommonDataProvider.Instance(); dp.CreateUpdateDeleteNews(post, DataAction.Create, out status); //强制清除匹配的缓存项 ClearNewsSetTopNCache (post.Language, post.ClassCode,Globals.GetSiteSetting.NewsListTopN); return status; }
0
相关文章