ASP.NET缓存总结

来源:岁月联盟 编辑:exp 时间:2012-07-28

一、缓存概念,缓存的好处、类型。
           缓存是一种用空间换取时间的技术,通俗点也就是说把你得到的数据存放在内存中一段时间,在这短时间内服务器不去读取数据库、或是真实的数据源,而是读取你存放在内存中的数据,这里你会疑惑怎么设置存放数据,能存放什么样子的数据,存放时间的设置,真实数据源数据改变服务器不就读取存在偏差?别急,下面慢慢会说到的。。
           缓存的好处,缓存是网站性能优化不可缺少的一种数据处理机制,他能有效的缓解数据库压力,例如,网站每分钟的点击率为100万,如果不使用缓存的静态页面,这里也没有viewstate的情况下(viewstate会产生大量的字符串,对服务器交互数据是一种压力,所以一般页面是要禁用viewstate,采用缓存的),只能是用户点击一次该页面,这个页面就读取一次数据库,这样给数据库造成的压力可想而知,如果这里我们使用了缓存的话,设置缓存有效期为1分钟,则这一分钟只内,点击100万次跟点击一次是一样的,都是读取一次数据库,数据源是被缓存在内存中了。
            asp.net中的缓存主要分为:页面缓存,数据源缓存,自定义数据缓存这三种主要类型。
二、数据缓存
[csharp]
public partial class WebForm1 : System.Web.UI.Page 
    { 
        protected void Page_Load(object sender, EventArgs e) 
        { 
            //  Cache["date"]=要缓存的数据;   这里是自定义缓存的简单声明使用 
            string datastr = DateTime.Now.ToLongTimeString(); 
            Response.Write("第一个输出时间:"+datastr+"</br>");  //这里读取的当前的时间,刷新页面时,这里的时间会随着变化。 
 
            if (Cache["date"] == null) //判断是否存在value值为date的缓存是否存在 
            { 
                Cache["date"] = datastr; 
                Response.Write("第二个输出时间为:"+Cache["date"] + "这里读取的当前的时间");   //这里读取的当前的时间,刷新页面时,这里的时间会随着变化。 
            } 
            else 
            { 
                Response.Write(Cache["date"] + "这里是从缓存中读取的时间");//这里读取的缓存中的时间,刷新页面时,这里的随着时间变化,不会变化。 
            } 
        } 
    } 
上面数据缓存由于没有设置缓存的过期时间,所以第一个输出时间为当前时间(刷新页面会变),第二个输出时间会一直为第一次存入缓存的时间(刷新页面不变)。
下面我们给数据缓存添加一些实用的参数(上代码)。
[csharp] 
protected void Page_Load(object sender, EventArgs e) 
        { 
            string ids=""; 
            Maticsoft.BLL.ScriptsBak bll = new Maticsoft.BLL.ScriptsBak(); 
            List<Maticsoft.Model.ScriptsBak> list = new List<Maticsoft.Model.ScriptsBak>(); 
            list = bll.GetAll(); 
            for (int i = 0; i < list.Count; i++) 
            { 
                ids += list[i].ScriptId.ToString()+"--"; 
            } 
            ids = ids + "完";  //这里的ids为从数据库中读取表中的id值然后用--链接起来的一个字符串 
            if (Cache["key"] == null) 
            { 
                Cache.Insert("key", ids, null, DateTime.Now.AddSeconds(40), System.Web.Caching.Cache.NoSlidingExpiration);  //这里给数据加缓存,设置缓存时间 
                //"key"为缓存的键,ids为缓存起来的值,null为缓存依赖项,这里没有使用缓存依赖项,所以为null,下面会详细介绍缓存依赖项 
                   //null后面为缓存的时间为40秒 
                  //最后一个参数为设置时间的格式,ASP.NET允许你设置一个绝对过期时间或滑动过期时间,但不能同时使用, 
                  //我们这里设置的为绝对过期时间,也就是没刷新一次页面后缓存数据为40秒,40秒后会从数据库中重新获取。  
                Response.Write("cache加载为---" + Cache["key"] + "</br>"); 
            } 
            else 
            { 
                Response.Write("cache加载为---" + Cache["key"] + "</br>"); 
            } 
            Response.Write("直接加载为---" + ids + "</br>"); 
        } 

数据缓存:将一些耗费时间的条目加入到一个对象缓存集合中,以键值的方式存储。我们可以通过使用Cache.Insert()方法来设置缓存的过期,优先级,依赖项等。
三、页面缓存

[csharp] 
protected void Page_Load(object sender, EventArgs e) 
       { 
           string date = DateTime.Now.ToString(); 
           Response.Write(date); 
       } 

[csharp] 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="cache.WebForm1" %> 
<%@ OutputCache Duration="10" VaryByParam="none" %>   
<!---添加上这一句代码意思是,添加此页面缓存十秒,这十秒之内,刷新页面将读缓存起来页面的值,不再执行Page_Load方法。 
     Page_Load方法是每十秒执行一次--> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <div> 
     
    </div> 
</body> 
</html> 

<%@ OutputCache Duration="10" VaryByParam="none" %> 这条指令标签为该页面添加缓存,Duration这个参数指定页面缓存时间为10秒,VaryByParam这个指定页面参数,也就是这样子的,打个比方,例如这样一个页面http://www.cnblogs.com/knowledgesea/admin/EditPosts.aspx?postid=2536603&update=1,那么他的参数也就是postid和update,如果这样页面我们可以把指令标签写为<%@ OutputCache Duration="10" VaryByParam="postid;update" %> 参数与参数之间用分号隔开,这样子也就吧每个单独的页面缓存起来了,他缓存的就是postid=2536603&update=1或者postid=1&update=2等等不一样的参数页面全部缓存起来。这里可以使用一个简便的方法,就是<%@ OutputCache Duration="10" VaryByParam="*" %>,缓存起来所有当前的页面下参数不一样的页面。
ASP.NET不会再执行页面的生命周期和相关代码而是直接使用缓存的页面,简单点理解也就是我注释中介绍的。
四、控件缓存
1.ObjectDataSource这样的数据源控件,可以在属性栏中找到相应的属性,进行设置,下面我列出个例子,设置启动缓存,缓存时间为10秒,时间类型为绝对时间。
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" EnableCaching="True" CacheDuration="10" CacheExpirationPolicy="Absolute"></asp:ObjectDataSource>
2.没有缓存属性的控件要加缓存
[csharp] 
protected void Page_Load(object sender, EventArgs e)   
        { 
            string date = DateTime.Now.ToString(); 
            TextBox1.Text = date; 
        } 

[csharp] 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="cache.WebForm1" %> 
<%@ OutputCache Duration="10" VaryByControl="TextBox1"%> 
<!--VaryByControl的参数为要缓存的控件id--> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
        <div> 
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
        </div> 
    </form> 
</body> 
</html> 

这里的TextBox控件就加了缓存,这里的缓存时间为10秒,也就是10秒内ASP.NET不会再执行页面的生命周期和相关代码而是直接使用缓存的页面。
五、缓存依赖
 
[csharp] 
protected void Page_Load(object sender, EventArgs e)   
        { 
            string str = ""; 
            if (Cache["key"] == null) 
            { 
                str = System.IO.File.ReadAllText(Server.MapPath("TextFile1.txt")); //读取TextFile1.txt文件中的数据 
                CacheDependency dp = new CacheDependency(Server.MapPath("TextFile1.txt"));//建立缓存依赖项dp 
                Cache.Insert("key", str, dp); 
                Response.Write(Cache["key"]);   //如果TextFile1.txt这个文件的内容不变就一直读取缓存中的数据,一旦TextFile1.txt文件中的数据改变里面重新读取TextFile1.txt文件中的数据 
            } 
            else 
            { 
                Response.Write(Cache["key"]); 
            } 
 
        } 

缓存依赖项使缓存依赖于其他资源,当依赖项更改时,缓存条目项将自动从缓存中移除。缓存依赖项可以是应用程序的 Cache 中的文件、目录或与其他对象的键。如果文件或目录更改,缓存就会过期。
六、配置文件中设置缓存
[csharp] 
<system.web> 
  <caching> 
    <outputCacheSettings> 
      <outputCacheProfiles> 
     <addname="ProductItemCacheProfile" duration="60"/> 
   </outputCacheProfiles> 
</outputCacheSettings> 
   </caching> 
</system.web> 

[csharp] 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="cache.WebForm1" %> 
<%@ OutputCache CacheProfile="ProductItemCacheProfile" VaryByParam="none" %> 
<!--这里的CacheProfile参数与配置文件中的保持一至--> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <div> 
     
    </div> 
</body> 
</html> 

这样就给页面添加了缓存为60秒的页面。
七、缓存的回调函数
 
[csharp] 
protected void Page_Load(object sender, EventArgs e)   
        { 
            string str = ""; 
            if (Cache["key"] == null) 
            { 
                str = System.IO.File.ReadAllText(Server.MapPath("TextFile1.txt")); //读取TextFile1.txt文件中的数据 
                CacheDependency dp = new CacheDependency(Server.MapPath("TextFile1.txt"));//建立缓存依赖项dp 
                Cache.Insert("key", str, dp, DateTime.Now.AddSeconds(20), Cache.NoSlidingExpiration, CacheItemPriority.Low, CacheItemRemovedCallback);  
                //CacheItemPriority这个参数为缓存的优先级他分好多种级别,为了防止缓存占满时系统自己删除缓存的优先顺序废除缓存的,后面的为回调函数的名称。 
                Response.Write(Cache["key"]);   //如果TextFile1.txt这个文件的内容不变就一直读取缓存中的数据,一旦TextFile1.txt文件中的数据改变里面重新读取TextFile1.txt文件中的数据 
            } 
            else 
            { 
                Response.Write(Cache["key"]); 
            } 
 
        } 
 
        public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason) //这个为缓存移除时的回调函数,一定要保持与 Cache.Insert()方法中的最后一个参数名字一致, 
            //这里使用了委托,你可以在 Cache.Insert()这个函数中转定义看到的,所以这里的格式就只能按我写的这种方法签名写。 
        { 
            System.IO.File.WriteAllText(Server.MapPath("log.txt"),"缓存移除原因为:"+reason.ToString()); 
        } 


作者:ysq5202121