ASP.NET 2.0缓存技术探讨


本文介绍通过缓存来提高网页的执行效率。

  1.       ASP.NET Output Caching

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

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

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

  l         定制Output Caching

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

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

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

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        TimeMsg.Text = DateTime.Now.ToString();
    }
   </script>//head以前。
    protected void Page_Load(object sender, EventArgs e)
    {
        TimeMsg.Text = DateTime.Now.ToString();
}
   <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache Duration="60" VaryByParam="none" %>

  l         示例讲解

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

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

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

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        TimeMsg.Text = DateTime.Now.ToString();
    }
   </script>//head以前。
    protected void Page_Load(object sender, EventArgs e)
    {
        TimeMsg.Text = DateTime.Now.ToString();
}
   <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache Duration="60" VaryByParam="none" %>//最上面

  l         由参数改变缓存内容

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

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

  最开始部分:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache Duration="60" VaryByParam="Name" %>
<script runat="server">
 
    protected void Page_Load(object sender, EventArgs e)
    {
        TimeMsg.Text = DateTime.Now.ToString("G");
    }
 
</script>

  Body内容:

        <span style="font-family: Verdana">Using the Output Cache</span><b>Authors by Name:</b>
        <table cellpadding="3" cellspacing="0" rules="all" style="border-left-color: black;
            border-bottom-color: black; width: 700px; border-top-color: black; border-collapse: collapse;
            background-color: #aaaadd; border-right-color: black">
            <tr>
                <td>
                    <a href="Default.aspx?Name=李阳">1</a></td>
                <td>
                    <a href="Default.aspx?Name=陈胜">2</a></td>
                <td>
                    <a href="Default.aspx?Name=夏秘密">3</a></td>
                <td>
                    <a href="Default.aspx?Name=范玲玲">4</a></td>
            </tr>
        </table>
        <br />
        <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:qimuConnectionString %>"
            SelectCommand="SELECT * FROM [tab1] WHERE ([Name] = @Name)">
            <SelectParameters>
                <asp:QueryStringParameter Name="Name" QueryStringField="Name" DefaultValue="李阳" />
            </SelectParameters>
        </asp:SqlDataSource>
        <br />
        <em>Last generated on:</em>
        <asp:Label ID="TimeMsg" runat="server"></asp:Label>&nbsp;

  显示效果:

  Using the Output CacheAuthors by Name:

  1

  2

  3

  4

  ID

  Name

  Sex

  1

  李阳

  男

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

  l         接受参数示例解说

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

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

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

  l         硬盘Output Cache

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

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

  l         使用DiskOutput Cache示例:

<%@ OutputCache Duration="3600" VaryByParam="name" DiskCacheable="true" %>
Web.Config文件中,
<configuration>
     <appSettings/>
     <system.web>
    <caching>
      <outputCache>
        <diskCache enabled="true" maxSizePerApp="2"(2M) />
      </outputCache>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="CacheFor60Seconds" duration="60" />
        </outputCacheProfiles>
      </outputCacheSettings>
      <!--
              <sqlCacheDependency enabled="true" pollTime="1000" >
                   <databases>
                       <add name="PubsDB" connectionStringName="pubsConnectionString" />
                   </databases>
              </sqlCacheDependency>
              -->
    </caching>
     </system.web>
</configuration>

  设置DiskOutput属性。

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

  l         回调缓存

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

  代码示例:

  ü         回调缓存示例

<%@ Page Language="VB" %>
<%@ OutputCache Duration="60" VaryByParam="none" %>
 
<script runat="server">
    Shared Function GetCurrentDate(ByVal context As HttpContext) As String
        Return Now.ToString()
    End Function
</script>
 
<html>
<head id="Head1" runat="server">
    <title>Post Cache Substitution</title>
</head>
<body>
    <form id="form1" runat="server">
        <h4>
            This page uses post cache substitution to insert a dynamic value into a cached page.</h4>
        <p>
            Time:
            <%= DateTime.Now.ToString() %>
        </p>
        <p>
            <b>Real Time:
                <asp:Substitution ID="Substitution1" runat="server" MethodName="GetCurrentDate" />
            </b>
        </p>
    </form>
</body>
</html>

  ü         通过API实现回调缓存

<%@ Page Language="VB" %>
<%@ OutputCache Duration="60" VaryByParam = "none" %>
 
<script runat="server">
 
Shared Function GetCurrentDate(context As HttpContext) As String
 
    return DateTime.Now.ToString()
End Function
 
</script>
 
<html>
<head id="Head1" runat="server">
    <title>Post Cache Substitution</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <b>This page uses post cache substitution to insert a dynamic value into a cached page.</b>
    <br /><br />
    Time: <%= DateTime.Now.ToString() %>
    <br /><br />
    <b>  
    Real Time: <% Response.WriteSubstitution(New HttpResponseSubstitutionCallback(AddressOf GetCurrentDate)) %>
    </b>
    </div>
    </div>
    </form>
</body>
</html>

  ü         通过使用SubStitution来实现缓存

  l         使用API定制缓存

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

  ü         Response.Cache.SetExpires(Now.AddSeconds(60))

   Response.Cache.SetCacheability(HttpCacheability.Public)

  2.       Page Fragment Caching

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

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

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

  用户控件页面设置:

<%@ Control Language="vb" %>
<%@ OutputCache Duration="60" VaryByParam="none" %>

  调用控件页面设置:

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

  Body部分:

     <h3>
        <font face="Verdana">Fragment Caching</font></h3>
    <Acme:DataControl runat="server" />
    <br>
    <i>页面最后被访问于:</i>
    <asp:Label ID="TimeMsg" runat="server" />

  l         接受控件传参数修改

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

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

  用户控件页面设置:

<%@ Control Language="VB" ClassName="FragCtrlwithAPI" %>
<%@ OutputCache Duration="60" VaryByControl="pickstate" %>
 
<script runat="server">
    Private duration As TimeSpan
   
    Sub Page_Load(ByVal sender As Object, 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 Object, ByVal e As EventArgs)
        Label1.Text = Now.ToString("G")
        Label2.Text = Now.Add(CachePolicy.Duration).ToString("G")
    End Sub
</script>
 
<div style="border: dotted 1px blue; padding: 5px; background-color: #eeeeee;">
    <asp:DropDownList ID="pickstate" runat="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:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"
        SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors] where state=@state"
        ProviderName="System.Data.SqlClient">
        <SelectParameters>
            <asp:ControlParameter ControlID="pickstate" DefaultValue="CA" Name="state" PropertyName="SelectedValue" />
        </SelectParameters>
    </asp:SqlDataSource>
    <asp:GridView ID="GridView1" runat="server" DataSourceID="sqldatasource1" />
    <p>
       控件被建立于<asp:Label ID="Label1" runat="server" Text="Label"/><br />
        控件被销毁<asp:Label ID="Label2" runat="server" Text="Label"/><br />     
    </p>
</div>

  调用控件页面设置:

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

  Body部分:

            <acme:FragCtrl ID="FragCtrl1" runat="server" />

   当前时间:

            <%=Now.ToString("G") %>
            <asp:Button ID="Button2" runat="server" Text="Refresh" />

  3.       Data Caching(数据缓存)

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

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

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

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

<%@ Page Language="vb" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
 
<html>
 
<script runat="server">
    Sub Page_Load(ByVal Src As Object, 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 = New SqlConnection(ConfigurationManager.ConnectionStrings("pubsConnectionString").ConnectionString)
            MyCommand = New SqlDataAdapter("select * from Authors", 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
 </script>
 
<body>
    <form id="Form1" runat="server">
        <h3>
            <font face="Verdana">Caching Data</font></h3>
        <asp:GridView ID="MyGrid" runat="server">
        </asp:GridView>
        <p>
            <i>
                <asp:Label ID="CacheMsg" 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” –ed
aspnet_regsql.exe –s “.SQLExPress” –E –d “pubs” –et –t  “authors”
<%@ OutputCache Duration = “999999” SqlDependency = “Pubs:Authors” VaryByParam = “none”%>

  5.       Cache Configuration

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

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

<configuration>
     <appSettings/>
     <system.web>
    <caching>
      <outputCache>
        <diskCache enabled="true" maxSizePerApp="2"(2M) />
      </outputCache>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="CacheFor60Seconds" duration="60" />
        </outputCacheProfiles>
      </outputCacheSettings>
      <!--
              <sqlCacheDependency enabled="true" pollTime="1000" >
                   <databases>
                       <add name="PubsDB" connectionStringName="pubsConnectionString" />
                   </databases>
              </sqlCacheDependency>
              -->
    </caching>
     </system.web>
</configuration>

  6.       总结

  l         Output Caching

  l         Fragment Caching

  l         Data Caching

  l         SQL Cache

  l         Cache Configuration


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3