ASP.NET 2.0缓存技术探讨

2014 年 12 月 29 日3230

  1.ASP.NET Output Caching

  当一个网页频繁被访问的时候,我们可以通过把整个网页缓存来提高执行效率。这样作的优点是,当用户再次访问这个网页的时候,被格式化好的HTML会被直接送显。

  为什么会存在这种效果呢?我们通过ASP.NET的基本运行机制来解释这个问题。ASP.NET是一个动态的服务器,当用户从客户端提供一个请求的时候,那么服务端的IIS接受到请求,然后根据用户的提示执行相应的代码。执行代码之后生成一个结果。这个结果会被缓存成一个HTML放在Server端,然后通过响应用户的Request将这个HTML传送到客户端。在这之中我们发现,很多时候,用户的请求实际上并没有多大的变化,可能请求的都是相同的内容。这时候执行一次代码的成本就会相当的高。既然我们已经生成了一个HTML,我们何必要在重新执行一次代码呢?我们直接把HTML送显就可以了。

  OutputCache是一项非常有效的增强访问性能的技术,由于IIS的一些特性,默认情况下OutputCache是打开的,但是要对一些请求进行缓存,还需要开发者进行定制。

  定制Output Caching

  对于OutputCaching的定制,我们有两种方法,一种是基于底层的API技术,一种是基于高层的@OutputCaching,一旦OutputCaching被定制过,那么这个网页就会在第一次被访问的时候生成cache,直到请求过期为止。

  我们着重点是使用高层的@OutputCaching标签来设置,因为API技术的编程难度比较大,和ASP.NET快速编程理念不相符。

  代码示例:通过使用OutputCache定义一个缓存页,显示当前时间,大家可以看到,当这个页面被缓存之后,刷新时,当前时间显示不发生变化。

  <t runat="server">

  protected voID Page_Load(t sender, EventArgs e)

  TimeMsg.Text = DateTime.Now.ToString();

  </t>//head以前。

  protected voID Page_Load(t sender, EventArgs e)

  TimeMsg.Text = DateTime.Now.ToString();

  <%@ Page Language="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default" %>

  <%@ OutputCache Duration="60" VaryBym="none" %>

  示例讲解

  在这个页面中<%@ Output Cache Duration = “60” VaryBym=“none”%>

  这段话定义了页面将要被缓存,并且,其缓存时间为60秒,并在一个页面被缓存之后,通过定义VaryBym属性,它不会因为request接受的参数而改变,只有在60秒之后,页面自动清除缓存,此时,第一个访问提供了新的缓存。

  代码示例:数据访问的小示例,相对显示当前数据示例,这个示例更能显示缓存页之后刷新的性能优势。

  <t runat="server">

  protected voID Page_Load(t sender, EventArgs e)

  TimeMsg.Text = DateTime.Now.ToString();

  </t>//head以前。

  protected voID Page_Load(t sender, EventArgs e)

  TimeMsg.Text = DateTime.Now.ToString();

  <%@ Page Language="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default" %>

  <%@ OutputCache Duration="60" VaryBym="none" %>//最上面

  由参数改变缓存内容

  有些时候我们需要根据用户的请求来生成页面,但是用户的请求只有有限的几种组合,这个时候就可以根据用户请求来生成几种缓存页面,来进行缓存。

  代码示例:接受参数示例,根据用户选择不同的Name显示不同的数据库内容。

  最开始部分:

  <%@ Page Language="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default" %>

  <%@ OutputCache Duration="60" VaryBym="Name" %>

  <t runat="server">

  protected voID Page_Load(t sender, EventArgs e)

  TimeMsg.Text = DateTime.Now.ToString("G");

  </t>

  Body内容:

  <span>Using theOutputCache</span><b>Authors by Name:</b>

  <table cellpadding="3" cellspacing="0"rules="all"style="border-center-color: black; border-bottom-color:black; wIDth: 700px; border-top-color:black; border-collapse:collapse; background-color: #aaaadd; border-center-color:black"> <tr> <td> <ahref="Default.aspx?Name=李阳">1</a></td> <td><a href="Default.aspx?Name=陈胜">2</a></td><td> <ahref="Default.aspx?Name=夏秘密">3</a></td> <td><a href="Default.aspx?Name=范玲玲">4</a></td></tr> </table>

  <br />

  <asp:GrIDViewrunat="server"DataSourceID="SqlDataSource1">

  </asp:GrIDView>

  <asp:SqlDataSourcerunat="server"ConnectionString="<%$ConnectionStrings:qimuConnectionString%>"

  SelectCommand="SELECT * FROM [tab1] WHERE ([Name]=@Name)">

  <Selectmeters>

  <asp:QueryStringmeterQueryStringField="Name"DefaultValue="李阳" />

  </Selectmeters>

  </asp:SqlDataSource>

  <br />

  <em>Last generated on:</em>

  <asp:LabelID="TimeMsg"runat="server"></asp:Label>

  显示效果:

  Using the Output CacheAuthors by Name:

  1

  2

  3

  4

  ID

  Name

  Sex

  1

  李阳

  男

  Last generated on: 2009-5-10 0:29:13

  接受参数示例解说

  关键语句<%@ Output Cache Duration = “60” VaryBym = “Name”%>

  上面显示一个数据库查询示例,并在页面下端放置一个访问的当前时间显示,可以清楚的看到,对于每个不同的参数,一分钟之内的访问会得到同一个时间戳,这表明用户在这个时间内访问的视同一个cache。

  注意:不足是在60秒以内数据库做出改变,不能显示更新的显示,需要处理这个问题还需要其他的设置。

  硬盘Output Cache

  默认情况下,OutputCache会被缓存到硬盘上。我们可以通过修改diskcacheenable的属性来设置其是否缓存,还可以通过在webconfig里配置缓存文件的大小。

  在使用程序的时候,我们常用内存缓存和交换区缓存,硬盘缓存技术我们可能用的不是很多,因为觉得硬盘速度慢,或者交互起来有问题。实际上,由于服务器现在占用内存都比较多,尤其是大型的应用。所以在IIS服务默认是把硬盘服务是打开的。

  使用DiskOutput Cache示例:

  <%@ OutputCache Duration="3600"VaryBym="Name"DiskCacheable="true" %>

  Web.Config文件中,

  <configuration>

  <appSettings/>

  <system.web>

  <caching>

  <outputCache>

  <diskCache enabled="true" maxSizePerApp="2"(2M) />

  </outputCache>

  <outputCacheSettings>

  <outputCacheProfiles>

  <add duration="60" />

  </outputCacheProfiles>

  </outputCacheSettings>

  <!--

  <sqlCacheDependency enabled="true" pollTime="1000" >

  <databases>

  <addconnectionStringName="pubsConnectionString"/>

  </databases>

  </sqlCacheDependency>

  -->

  </caching>

  </system.web>

  </configuration>

  设置DiskOutput属性。

  指定硬盘缓存时,指定时间要相应的大一些。硬盘访问速度相对慢一点。(VS 2005正式版已经删除了这一个功能,汗!)

  回调缓存

  通过设置回调缓存机制,可以针对每个请求在页面中插入动态的部分,以弥补单独使用静态缓存的不足。

  代码示例:

  回调缓存示例

  <%@ Page Language="VB" %>

  <%@ OutputCache Duration="60" VaryBym="none" %>

  <t runat="server">

  Shared n GetCurrentDate(ByVal context As HttpContext)AsString

  Return Now.ToString()

  End n

  </t>

  <html>

  <head runat="server">

  <title>Post Cache Substitution</title>

  </head>

  <body>

  <form runat="server">

  <h4>

  This page uses post cache substitution to insert a dynamicvalueinto a cached page.</h4>

  <p>

  Time:

  <%= DateTime.Now.ToString() %>

  </p>

  <p>

  <b>Real Time:

  <asp:Substitutionrunat="server"MethodName="GetCurrentDate" />

  </b>

  </p>

  </form>

  </body>

  </html>

  通过API实现回调缓存

  <%@ Page Language="VB" %>

  <%@ OutputCache Duration="60" VaryBym = "none" %>

  <t runat="server">

  Shared n GetCurrentDate(context As HttpContext) As String

  return DateTime.Now.ToString()

  End n

  </t>

  <html>

  <head runat="server">

  <title>Post Cache Substitution</title>

  </head>

  <body>

  <form runat="server">

  <div>

  <b>This page uses post cache substitution to insertadynamic value into a cached page.</b>

  <br /><br />

  Time: <%= DateTime.Now.ToString() %>

  <br /><br />

  <b>

  Real Time: <%Response.WriteSubstitution(NewHttpResponseSubstitutionCallback(AddressOfGetCurrentDate))%>

  </b>

  </div>

  </div>

  </form>

  </body>

  </html>

  通过使用SubStitution来实现缓存

  使用API定制缓存

  如果需要对缓存进行更详细的设置,可以通过设置System.Web.HttpCachePolicy属性来进行配置下面这个语句和我们<%@Output Cache Duration = “60” VaryBym=“none”%>完全一样üResponse.Cache.SetExpires(Now.AddSeconds(60))

  Response.Cache.SetCacheability(HttpCacheability.Public)

  2.Page Fragment Caching

  作为Output的缓存的附加功能,还提供一种缓存技术,专门用于缓存用户控件或者网页中的一部分东西。可以指定没一部分或者某一个区域不被缓存。

  在页面中,指定返回参数,来决定控件被缓存的部分。使用语句VaryBym语句指定控件更具参数来改变。

  示例:通过返回参数改变缓存内容示例

  用户控件页面设置:

  <%@ Control Language="vb" %>

  <%@ OutputCache Duration="60" VaryBym="none" %>

  调用控件页面设置:

  <%@ Register TagPrefix="Acme"TagName="DataControl"Src="datactrl.ascx" %>

  Body部分:

  <h3>

  <fontface="Verdana">FragmentCaching</font></h3>

  <Acme:DataControl runat="server" />

  <br>

  <i>页面最后被访问于:</i>

  <asp:Label runat="server" />

  接受控件传参数修改

  缓存用户控件同样还可以使用控件作为参数来源。通过指定控件作为缓存控件的参数来源,可以达到缓存控件数据的目的。

  示例:通过控件参数改变缓存内容示例

  用户控件页面设置:

  <%@ Control Language="VB" ClassName="FragCtrlwithAPI"%>

  <%@ OutputCache Duration="60"VaryByControl="pickstate"%>

  <t runat="server">

  Private duration As TimeSpan

  Sub Page_Load(ByVal sender As t, ByVal E As EventArgs)

  If (pickstate.SelectedValue = "CA") Then

  duration = New TimeSpan(0, 0, 10)

  CachePolicy.Duration = duration

  End If

  End Sub

  Sub Page_PreRender(ByVal sender As t, ByVal e As EventArgs)

  Label1.Text = Now.ToString("G")

  Label2.Text = Now.Add(CachePolicy.Duration).ToString("G")

  End Sub

  </t>

  <div>

  <asp:DropDownListrunat="server"AutoPostBack=true>

  <asp:ListItem Text="CA" Value="CA" />

  <asp:ListItem Text="UT" Value="UT" />

  <asp:ListItem Text="MD" Value="MD" />

  <asp:ListItem Text="OR" Value="OR" />

  <asp:ListItem Text="MI" Value="MI" />

  <asp:ListItem Text="TN" Value="TN" />

  </asp:DropDownList>

  <asp:SqlDataSourcerunat="server"ConnectionString="<%$ConnectionStrings:pubsConnectionString%>"

  SelectCommand="SELECT [au_ID], [au_lName], [au_fName],[phone],[address], [city], [state], [zip], [contract] FROM[authors] wherestate=@state"

  ProvIDerName="System.Data.SqlClient">

  <Selectmeters>

  <asp:Controlmeter ControlID="pickstate"DefaultValue="CA"Name="state" PropertyName="SelectedValue"/>

  </Selectmeters>

  </asp:SqlDataSource>

  <asp:GrIDViewrunat="server"DataSourceID="sqldatasource1" />

  <p>

  控件被建立于<asp:Labelrunat="server"Text="Label"/><br />

  控件被销毁<asp:Labelrunat="server"Text="Label"/><br />

  </p>

  </div>

  调用控件页面设置:

  <%@ Register Src="datactrlnew.ascx"TagName="FragCtrl"TagPrefix="acme" %>

  Body部分:

  <acme:FragCtrl runat="server" />

  当前时间:

  <%=Now.ToString("G") %>

  <asp:Button runat="server"Text="Refresh"/>

  3.Data Caching(数据缓存)

  ASP.NET提供了一种非常快捷的方法进行数据库缓存,用户可以非常方便的对页面变量进行缓存。并以此提高程序效率。

  一个页面变量的缓存生命周期与应用程序的缓存生命周期相同。

  同时对后台数据进行修改的时候,还需要对Cache进行相应的处理。

  示例:使用数据缓存示例:

  <%@ Page Language="vb" %>

  <%@ Import Namespace="System.Data" %>

  <%@ Import Namespace="System.Data.SqlClient" %>

  <html>

  <t runat="server">

  Sub Page_Load(ByVal Src As t, ByVal E As EventArgs)

  Dim Source As DataView

  " try to retrieve item from cache

  " if it"s not there, add it

  Source = Cache("MyDataSet")

  If Source Is Nothing Then

  Dim MyConnection As SqlConnection

  Dim MyCommand As SqlDataAdapter

  MyConnection =NewSqlConnection(ConfigurationManager.ConnectionStrings("pubsConnectionString").ConnectionString)

  MyCommand = New SqlDataAdapter("select * fromAuthors",MyConnection)

  Dim ds As New DataSet

  MyCommand.Fill(ds, "Authors")

  Source = New DataView(ds.Tables("Authors"))

  Cache("MyDataSet") = Source

  CacheMsg.Text = "Dataset created explicitly"

  Else

  CacheMsg.Text = "Dataset retrieved from cache"

  End If

  MyGrID.DataSource = Source

  MyGrID.DataBind()

  End Sub

  </t>

  <body>

  <form runat="server">

  <h3>

  <fontface="Verdana">CachingData</font></h3>

  <asp:GrIDView runat="server">

  </asp:GrIDView>

  <p>

  <i>

  <asp:Label runat="server" /></i>

  </p>

  </form>

  </body>

  </html>

  4.SQL Cache

  前面的例子中,我们使用的是缓存技术,一旦时间到,无论服务器端的数据是否改变都会释放缓存,下面介绍的例子,通过配置数据库连接池,只有当数据库数据被改变的时候,缓存才会改变。

  示例:配置连接池示例

  开一个DOS窗口->找到aspnet_regsql.exe工具(常用参数:-s指定我们注册的服务器-E使用Windows授权模式-D指定数据库DataBase名字-ED缓存生效)->

  aspnet_regsql.exe –s “.SQLExPress” –E –d“pubs”–edaspnet_regsql.exe –s “.SQLExPress” –E –d “pubs” –et–t“authors”

  <%@ OutputCache Duration = “999999” SqlDependency=“Pubs:Authors” VaryBym = “none”%>

  5.Cache Configuration

  可以通过在webconfig里配置不同的缓存描述,在页面中调用该描述来减少重复定义缓存描述的工作量。

  示例:缓存描述定义示例:

  <configuration>

  <appSettings/>

  <system.web>

  <caching>

  <outputCache>

  <diskCache enabled="true" maxSizePerApp="2"(2M) />

  </outputCache>

  <outputCacheSettings>

  <outputCacheProfiles>

  <add duration="60" />

  </outputCacheProfiles>

  </outputCacheSettings>

  <!--

  <sqlCacheDependency enabled="true" pollTime="1000" >

  <databases>

  <addconnectionStringName="pubsConnectionString"/>

  </databases>

  </sqlCacheDependency>

  -->

  </caching>

  </system.web>

  </configuration>

  6.总结

  Output Caching

  Fragment Caching

  Data Caching

  SQL Cache

  Cache Configuration

  编辑推荐

  ASP.NET视频教程

  ASP.NET MVC框架视频教程

【来源:51cto】

(责任编辑:和讯网站)

0 0