Asp.Net缓存

希望减少每次数据库的范围可以考虑用缓存。。

缓存分永久缓存、时间缓存、和依赖缓存。。

1.永久缓存

if (Cache["cache"]!=null)

{
  
}else
{
  Cache.Insert("cache", "test");
}

2.时间缓存。时间过期缓存自动清空

if (Cache["cache"]!=null)
{

}else
{

  //第三个参数基本为null 时间都是秒。下面表示缓存10秒后清空。
  Cache.Insert("cache", "test",null,DateTime.Now.AddSeconds(10),System.Web.Caching.Cache.NoSlidingExpiration);
}

3.依赖缓存。

if (Cache["data"] == null)
{

  //依赖缓存基本都是依赖某个文件等。。可以是永久依赖也可以时间依赖

string fileUrl = Server.MapPath("Key.txt");
System.Web.Caching.CacheDependency cdp = new System.Web.Caching.CacheDependency(fileUrl);
StreamReader sr = new StreamReader(fileUrl, System.Text.Encoding.GetEncoding("GB2312"));
string s = sr.ReadLine();
sr.Close();
Cache.Insert("data", s, cdp);

}

posted @ 2015-04-07 17:40  只需要一个眼神  阅读(118)  评论(0编辑  收藏  举报