cache实例

参考文章:

http://www.cnblogs.com/freshman0216/archive/2008/07/15/1243685.html

http://www.cnblogs.com/thinhunan/archive/2005/10/05/248887.html
在使用Cache时,尽量使用System.Web.HttpRuntime.Cache(亦可以用System.Web.Hosting.HostingEnvironment.Cache),而不是HttpContext.Current.Cache。
 System.Web.Caching.Cache myCache = System.Web.HttpRuntime.Cache;  //或者System.Web.Hosting.HostingEnvironment.Cache;
 if (myCache["myKey"] != null)  //或者用myCache.Get("myKey")
 {
     return myCache["myKey"] as ... ;  //转成其它数据结构
 }
 ...  //如果myCache["myKey"]为空,取出数据放到myDataSource变量里
 myCache.Insert("myKey",myDataSource,...);
 

缓存某分类的新闻列表:

public List<NewsInfo> GetPageNewsByClassId(decimal newsClassId, int startIndex, int pageSize)
{
    List<NewsInfo> news = new List<NewsInfo>();
    Cache cache = System.Web.Hosting.HostingEnvironment.Cache;
    string cacheKey = string.Format("MySolutionName.GetPageNewsByClassId.{0}.{1}", newsClassId, startIndex);  //解决方案.方法.参数
    if (cache.Get(cacheKey) == null)
    {
        news = myMappingLogic.GetPageNewsByClassId(newsClassId, startIndex, startIndex + pageSize);  //映射层对象的方法

        if (news != null)  //缺少判断极可能导致页面取到null值而出错
            cache.Insert(cacheKey, news, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);  //五分钟后清除,不管有没有人访问

    //cache.Insert(cacheKey, news, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(20));  //最后一次访问的20秒后清除。
    }
    else
    {
        news = cache.Get(cacheKey) as List<NewsInfo>;
    }
    return news;
}

 

 

posted @ 2010-01-29 14:43  DaCHun  阅读(806)  评论(1编辑  收藏  举报