详解ASP.NET缓存的工作原理

开发 后端
本文将从ASP.NET缓存讲起,从缓存的定义,工作原理开始,一直到缓存优先级等等内容。

这里我们将介绍ASP.NET缓存的工作原理,包括简单的定义,数据缓存以及缓存的设置等等内容。希望本文能对大家今后的工作有所帮助。

[[6772]]

#T#

介绍

缓存是在内存存储数据的一项技术,也是ASP.NET中提供的重要特性之一。例如你可以在复杂查询的时候缓存数据,这样后来的请求就不需要从数据库中取数据,而是直接从缓存中获取。通过使用缓存可以提高应用程序的性能。

主要有两种类型的缓存:

1.输出缓存Output caching

2.数据缓存Data caching

1. 输出缓存(Output Caching)

使用输出缓存,你可以缓存最后输出的HTML页面,当相同的页面再次请求的时候,ASP.NET不会再执行页面的生命周期和相关代码而是直接使用缓存的页面,语法如下:

  1. <%@ OutputCache Duration=”60” VaryByParam=”None”  %>  

Duration 属性设置页面将被缓存60妙。任何的用户请求都会被缓存,在缓冲的60秒内相同的请求都会直接使用缓存的页面。当缓存过期后ASP.NET会再次执行页面代码并且为下一个60秒创建一个新的HTML缓存。

  1.  <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" 
  2.         CodeFile="OutputCachingTest.aspx.cs" Inherits="OutputCachingTest" Title="Untitled Page" %> 
  3.  <%@ OutputCache Duration="20" VaryByParam="None" %> 
  4.  <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">   
  5.    <div class="title">Output Cache</div> 
  6.    Date: <asp:Label ID="lblDate" runat="server" Text="" /> 
  7.    Time: <asp:Label ID="lblTime" runat="server" Text="" />         
  8.  </asp:Content> 
  9. protected void Page_Load(object sender, EventArgs e)  
  10. {  
  11.    lblDate.Text = DateTime.Now.ToShortDateString();  
  12.    lblTime.Text = DateTime.Now.ToLongTimeString();   
  13. }  

在这个例子中页面将被缓存20秒。

通过查询字符串缓存(Cache by Query String )
在实际应用中页面往往会根据一些参数动态的改变页面的内容。如果你的页面是通过查询字符串来获取信息的,你可以根据查询字符串很容易的缓存页面的不同拷贝。VarByParam=”None”指定ASP.NET只存储缓存页面的一个拷贝。VarByParam=”*” 指定ASP.NET根据不同的查询字符串存储不同的缓存页面。

  1. <%@ OutputCache Duration="60" VaryByParam="*" %> 
  2.  
  3. <div align="right"> 
  4.    <a href="OutputCachingTest2.aspx">No Query String</a> |   
  5.    <a href="OutputCachingTest2.aspx?id=1">ID 1</a> |   
  6.    <a href="OutputCachingTest2.aspx?id=2">ID 2</a> |   
  7.    <a href="OutputCachingTest2.aspx?id=3">ID 3</a> |  
  8.    <a href="OutputCachingTest2.aspx?id=3&langid=1">ID 3</a> 
  9. </div>  

上面的例子中,在查询字符串中传了不同的ID.ASP.NET为每一个ID都存储了单独的缓存页面。这种方式会有一些问题就是当查询字符串范围很广的时候。这个时候我们可以在VarByParam 属性中指定重要的查询字符串变量的名字,如下:

  1. <%@OutputCacheDuration="60"VaryByParam="id;langid"%>  

这样,ASP.NET可以根据id” or “langid”来缓存不同的缓存版本。

自定义缓存(Custom Caching)

你也可以创建自定义的程序来缓存页面。ASP.NET提供了一种很便捷的方式来创建自定义缓存,使用VarByCustom属性指定自定义缓存类型的名字。

  1. %@OutputCacheDuration="20"VaryByParam="None"VaryByCustom="browser"

你还要创建为缓存生成自定义字符串的方法,如下:

  1. public override stringGetVaryByCustomString(HttpContext context, stringcustom)  
  2. {  
  3.     if(custom == "browser")  
  4.     {  
  5.        returncontext.Request.Browser.Browser +  
  6.               context.Request.Browser.MajorVersion;  
  7.     }  
  8.     else 
  9.    {  
  10.        return base.GetVaryByCustomString(context, custom);  
  11.     }  
  12. }  

这个方法必须写在global.asax文件中。ASP.NET使用该方法返回的字符串来实现缓存,如果这个方法在不同的请求中返回相同的字符串,ASP.NET就会使用缓存的页面,否则就会生成新的缓存版本。

上面的例子中GetVaryByCustomString()方法根据浏览器的名字创建缓存字符串,ASP.NET会根据不同的浏览器请求创建不同版本的缓存。

控件缓存(Control Cache )
上面的缓存技术可以让你很容易的缓存整个页面,如果要缓存指定控件的内容,可以通过指定VaryByControl 属性来完成。

  1. <%@OutputCacheDuration="20"VaryByControl="MyControl_1"%> 

上面代码ASP.NET将会缓存MyControl_1控件20分钟。如果要根据一些属性值来缓存控件只需要将OutPutCache指令加入*.ascx页面。 

  1. <%@Control Language="C#"AutoEventWireup="true"CodeFile="MyControl.ascx.cs"Inherits="Controls_MyControl"%> 
  2. <%@OutputCacheDuration="20"VaryByControl="EmployeeID"%> 
  3. ......  
  4. ......  

VaryByControl=”EmployeeID”告诉ASP.NET根据控件中声明的EmployeeID属性来创建不同版本的缓存。

在 .ascx.cs 文件加入EmplyeeID属性为ASP.NET 缓存使用。

  1. private int_employeeID;  
  2. public intEmployeeID  
  3. {  
  4.    get{ return_employeeID; }  
  5.    set{ _employeeID = value; }  
  6. }  
  7.  
  8. protected voidPage_Load(objectsender, EventArgs e)  
  9. {  
  10.    lblDate.Text = DateTime.Now.ToShortDateString();  
  11.    lblTime.Text = DateTime.Now.ToLongTimeString();  
  12.  
  13.    lblEmployeeID.Text = EmployeeID.ToString();  
  14.  

在页面中增加控件并且设置 EmployeeID.

  1. <%@RegisterSrc="Controls/MyControl.ascx"TagName="MyControl"TagPrefix="uc1"%> 
  2. <asp:ContentIDasp:ContentID="Content1"ContentPlaceHolderID="ContentPlaceHolder1"runat="Server"> 
  3.     <divaligndivalign="center"> 
  4.         <uc1:MyControlIDuc1:MyControlID="MyControl1"runat="server"EmployeeID="1"></uc1:MyControl> 
  5.     </div> 
  6. </asp:Content> 

缓存配置文件(Cache Profile )
web.config可以配置缓存相关的设置,

  1. <system.web> 
  2.   <caching> 
  3.     <outputCacheSettings> 
  4.       <outputCacheProfiles> 
  5.      <addnameaddname="ProductItemCacheProfile" duration="60"/> 
  6.    </outputCacheProfiles> 
  7. </outputCacheSettings> 
  8.    </caching> 
  9. </system.web> 

你可以通过设置 CacheProfile=”ProfileName” 属性 来使用上面的配置:

  1. %@OutputCacheCacheProfile="ProductItemCacheProfile"VaryByParam="None"% 

2. 数据缓存(Data Caching)

ASP.NET还提供了另一种灵活的缓存类型:数据缓存。你可以将一些耗费时间的条目加入到一个对象缓存集合中,以键值的方式存储。

Cache["Name"] = data;

我们可以通过使用Cache.Insert()方法来设置缓存的过期,优先级,依赖项等。

  1. date1 = DateTime.Now;  
  2. Cache.Insert("Date1", date1, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero); 

ASP.NET允许你设置一个绝对过期时间或滑动过期时间,但不能同时使用。

缓存依赖项Cache dependency

缓存依赖项使缓存依赖于其他资源,当依赖项更改时,缓存条目项将自动从缓存中移除。缓存依赖项可以是应用程序的 Cache 中的文件、目录或与其他对象的键。如果文件或目录更改,缓存就会过期。

  1. date2 = DateTime.Now;  
  2. string[] cacheKeys = { "Date1"};  
  3. CacheDependency cacheDepn = newCacheDependency(null, cacheKeys);  
  4. Cache.Insert("Date2", date2, cacheDepn); 

上面的例子“Date2”缓存对象依赖“Date1”缓存条目,当 “Date1” 对象过期后“Date2” 将会自动过期。CacheDependency(null, cacheKeys)中的第一个参数为空是由于我们只监视缓存键的更改情况。

回调函数和缓存优先级(Callback Method and Cache Priority)

ASP.NET允许我们写一个回调函数,当缓存条目从缓存中移除的时候触发。还可以设置缓存条目的优先级。

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.   DateTime? date1 = (DateTime?)Cache["Date1"];  
  4.   if (!date1.HasValue) // date1 == null  
  5.   {  
  6.     date1 = DateTime.Now;  
  7.     Cache.Insert("Date1", date1, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero,   
  8.                  CacheItemPriority.Default, new CacheItemRemovedCallback(CachedItemRemoveCallBack));  
  9.   }  
  10.  
  11.   DateTime? date2 = (DateTime?)Cache["Date2"];  
  12.   if (!date2.HasValue) // date2 == null  
  13.   {  
  14.     date2 = DateTime.Now;  
  15.     Cache.Insert("Date2", date2, null, DateTime.Now.AddSeconds(40), TimeSpan.Zero,   
  16.                  CacheItemPriority.Default, new CacheItemRemovedCallback(CachedItemRemoveCallBack));  
  17.   }  
  18.  
  19.   // Set values in labels  
  20.   lblDate.Text = date1.Value.ToShortDateString();  
  21.   lblTime.Text = date1.Value.ToLongTimeString();  
  22.  
  23.   lblDate1.Text = date2.Value.ToShortDateString();  
  24.   lblTime1.Text = date2.Value.ToLongTimeString();  
  25.  
  26. }  
  27.      
  28. private void CachedItemRemoveCallBack(string key, object value, CacheItemRemovedReason reason)  
  29. {  
  30.   if (key == "Date1" || key == "Date2")  
  31.   {   
  32.      Cache.Remove("Date1");  
  33.      Cache.Remove("Date2");  
  34.   }  

例子中创建了“Date1” 和 “Date2”缓存。“Date1” 在20秒后过期“Date2”为40秒。但是由于我们注册了移除的回调函数,当“Date1” 或 “Date2”其中一个过期都会执行CachedItemRemoveCallBack 方法,在这个方法中移除了两个缓存条目,ASP.NET还提供了处理缓存条目更新时的回调函数CacheItemUpdateCallback 。

原文标题:ASP.NET缓存

链接:http://www.cnblogs.com/carysun/archive/2009/11/08/AspDotNetCache.html

责任编辑:彭凡 来源: 博客园
相关推荐

2009-08-03 12:40:46

ASP.NET编程模型

2009-07-31 10:23:44

缓存页面ASP.NET缓存

2009-07-29 16:08:07

ASP和ASP.NET

2009-07-29 15:34:13

2009-07-31 10:33:54

ASP.NET页面输出

2009-07-29 14:35:34

页面输出缓存ASP.NET

2009-08-04 15:22:33

ASP.NET缓存机制

2009-07-29 10:35:51

ASP.NET缓存

2009-08-05 11:14:33

ASP.NET ISA

2009-07-22 16:25:41

ASP.NET AJA

2009-07-28 16:57:50

ASP.NET Ses

2009-07-24 10:14:22

ASP.NET开发

2009-07-23 13:19:51

2009-07-28 13:02:28

asp.net

2009-03-31 09:18:34

客户端内置对象ASP.NET

2009-08-03 18:35:51

ASP.NET数据缓存

2009-08-17 16:59:36

ASP.NET缓存机制

2009-05-11 13:48:00

ASP.NET 2.0缓存效率

2009-07-23 13:09:23

2009-08-03 18:47:12

ASP.NET数据缓存
点赞
收藏

51CTO技术栈公众号