免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1390 | 回复: 0
打印 上一主题 下一主题

ASP.NET 2.0(C#)(4) - Cache&SqlCacheDependency(缓存和SqlCacheDependency特性) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-03-25 20:37 |只看该作者 |倒序浏览
介绍
存是在计算中广泛使用的一种技术,通过将经常访问的数据或存取开销较大的数据保留在内存或硬盘中来提高性能。在 Web 应用程序的上下文中,缓存用于在 HTTP 请求之间保留页或数据,在重用它们时可以不必耗费资源重新创建。


关键
1、@OutputCache指令中的属性:
    Duration - 缓存时间(秒)
    VaryByParam - 根据使用 POST 或 GET 发送的名称/值对来改变缓存的结果(多参数用分号隔开)
    VaryByControl - 根据用户控件中的控件来改变缓存的片段(值是控件ID,多控件用分号隔开)
    CacheProfile - 调用配置文件中设置的缓存时间

2、增加数据缓存时用Cache.Insert,可以指定缓存时间

3、替换缓存(Substitution)- 回调函数要是静态的

4、SqlCacheDependency
配置文件中的配置
  1. <system.web>
  2.     <caching>
  3.       <sqlCacheDependency enabled="true" pollTime="轮询时间(毫秒)">
  4.         <databases>
  5.           <add name="名字" connectionStringName="连接字符串的名字" />
  6.         </databases>
  7.       </sqlCacheDependency>
  8.       <!-- 如果是SqlServer2005的话,则只需如下设置,因为SqlServer支持基于通知的缓存失效
  9.       <sqlCacheDependency enabled="true" />
  10.       -->
  11.     </caching>
  12.   </system.web>
复制代码
如果不是SqlServer2005的话,应该使用aspnet_regsql注册一下
aspnet_regsql.exe -S "server" -E -d "database" -ed
aspnet_regsql.exe -S "server" -E -d "database" -et -t "table"
如果是Sql验证的话要把-E换成,-U(用户名),-P(密码)


示例
页面输出缓存
  1. Cahce/Page.aspx
  2. <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Page.aspx.cs"
  3.     Inherits="Cahce_Page" Title="页面输出缓存" %>

  4. <%@ OutputCache Duration="10" VaryByParam="none" %>
  5. <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  6.     <p>
  7.         Duration="10" VaryByParam="none"
  8.     </p>
  9.     <p>
  10.         <%=DateTime.Now %>
  11.     </p>
  12. </asp:Content>

  13. API操作缓存
  14. Cahce/Page.aspx.cs
  15. using System;
  16. using System.Data;
  17. using System.Configuration;
  18. using System.Collections;
  19. using System.Web;
  20. using System.Web.Security;
  21. using System.Web.UI;
  22. using System.Web.UI.WebControls;
  23. using System.Web.UI.WebControls.WebParts;
  24. using System.Web.UI.HtmlControls;

  25. public partial class Cahce_Page : System.Web.UI.Page
  26. {
  27.     protected void Page_Load(object sender, EventArgs e)
  28.     {
  29.         /**//* 通过API设置缓存 不常用啊
  30.         
  31.         // 相当于@OutputCache指令中的Duration属性
  32.         Response.Cache.SetExpires(DateTime.Now.AddSeconds(10));
  33.         // 以指定响应能由客户端和共享(代理)缓存进行缓存。
  34.         Response.Cache.SetCacheability(HttpCacheability.Public);

  35.         // 过期时间可调
  36.         Response.Cache.SetSlidingExpiration(true);
  37.         
  38.         */
  39.     }
  40. }
  41. 页面输出缓存(VaryByParam)
  42. Cahce/PageByParam.aspx
  43. <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="PageByParam.aspx.cs"
  44.     Inherits="Cahce_PageByParam" Title="页面输出缓存(VaryByParam)" %>

  45. <%@ OutputCache CacheProfile="CacheTest" VaryByParam="p1;p2" %>
  46. <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  47.     <p>
  48.         CacheProfile="CacheTest" VaryByParam="p1;p2"
  49.         <br />
  50.         CacheProfile="CacheTest" - 从web.config中读信息
  51.         <br />
  52.         get或post方式都行
  53.     </p>
  54.     <p>
  55.         <a href="?p1=a&p2=b">第一组</a>
  56.         <br />
  57.         <a href="?p1=c&p2=d">第二组</a>
  58.         <br />
  59.         <a href="?p1=e&p2=f">第三组</a>
  60.     </p>
  61.     <p>
  62.         <%=DateTime.Now %>
  63.     </p>
  64. </asp:Content>

  65. 上面页所需的web.config中的配置
  66.   <system.web>
  67.     <caching>
  68.       <outputCacheSettings>
  69.         <outputCacheProfiles>
  70.           <add name="CacheTest" duration="10" />
  71.         </outputCacheProfiles>
  72.       </outputCacheSettings>
  73.     </caching>
  74.   </system.web>
  75. 页面输出缓存(VaryByControl)
  76. Cahce/CacheControl.ascx
  77. <%@ Control Language="C#" AutoEventWireup="true" CodeFile="CacheControl.ascx.cs"
  78.     Inherits="Cahce_CacheControl" %>
  79. <%@ OutputCache Duration="10" VaryByControl="DropDownList1" %>
  80. <p>
  81.     <%=DateTime.Now %>
  82. </p>
  83. <p>
  84.     <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="XmlDataSource1"
  85.         DataTextField="text" DataValueField="value">
  86.     </asp:DropDownList><asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Config/DropDownListData.xml">
  87.     </asp:XmlDataSource>
  88. </p>
  89. <p>
  90.     <asp:Button ID="btn" runat="Server" Text="提交" />
  91. </p>

  92. Cahce/PageByControl.aspx
  93. <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="PageByControl.aspx.cs"
  94.     Inherits="Cahce_PageByControl" Title="页面输出缓存(VaryByControl)" %>

  95. <%@ Register Src="CacheControl.ascx" TagName="CacheControl" TagPrefix="uc1" %>
  96. <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  97.     <p>
  98.         未经缓存设置的容器页:
  99.         <%=DateTime.Now %>
  100.     </p>
  101.     <p>
  102.         经过VaryByControl设置的用户控件,根据DropDownList的不同缓存不同的内容(用户控件中的@OutputCache指令为Duration="10"
  103.         VaryByControl="DropDownList1"):<br />
  104.         <uc1:CacheControl ID="CacheControl1" runat="server" />
  105.     </p>
  106. </asp:Content>
复制代码
数据缓存
  1. Cahce/Data.aspx
  2. <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Data.aspx.cs"
  3.     Inherits="Cahce_Data" Title="数据缓存" %>

  4. <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  5.     <p>
  6.         <asp:Label ID="lbl" runat="server" />
  7.     </p>
  8. </asp:Content>

  9. Cahce/Data.aspx.cs
  10. using System;
  11. using System.Data;
  12. using System.Configuration;
  13. using System.Collections;
  14. using System.Web;
  15. using System.Web.Security;
  16. using System.Web.UI;
  17. using System.Web.UI.WebControls;
  18. using System.Web.UI.WebControls.WebParts;
  19. using System.Web.UI.HtmlControls;

  20. public partial class Cahce_Data : System.Web.UI.Page
  21. {
  22.     protected void Page_Load(object sender, EventArgs e)
  23.     {
  24.         // 一看就懂
  25.         if (Cache["key"] == null)
  26.         {
  27.             Cache.Insert("key", DateTime.Now, null, DateTime.Now.AddSeconds(10), TimeSpan.Zero);
  28.         }

  29.         DateTime dt = (DateTime)Cache["key"];
  30.         lbl.Text = dt.ToString();
  31.     }
  32. }
复制代码
替换缓存(部分区域强行不使用缓存)
  1. Cahce/Substitution.aspx
  2. <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Substitution.aspx.cs"
  3.     Inherits="Cahce_Substitution" Title="替换缓存(部分区域强行不使用缓存)" %>

  4. <%@ OutputCache Duration="10" VaryByParam="none" %>
  5. <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  6.     <p>
  7.         Duration="10" VaryByParam="none"
  8.     </p>
  9.     <p>
  10.         <%=DateTime.Now %>
  11.     </p>
  12.     <p>
  13.         API 向返回当前日期的静态方法中插入动态回调,此回调在每次请求时都会执行<br />
  14.         <% Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetTime)); %>
  15.     </p>
  16.     <p>
  17.         使用Substitution 控件插入动态内容<br />
  18.         <asp:Substitution ID="Substitution1" runat="server" MethodName="GetTime" />
  19.     </p>
  20. </asp:Content>

  21. Cahce/Substitution.aspx.cs
  22. using System;
  23. using System.Data;
  24. using System.Configuration;
  25. using System.Collections;
  26. using System.Web;
  27. using System.Web.Security;
  28. using System.Web.UI;
  29. using System.Web.UI.WebControls;
  30. using System.Web.UI.WebControls.WebParts;
  31. using System.Web.UI.HtmlControls;

  32. public partial class Cahce_Substitution : System.Web.UI.Page
  33. {
  34.     protected void Page_Load(object sender, EventArgs e)
  35.     {

  36.     }

  37.     // 回调函数所调的静态方法
  38.     public static string GetTime(HttpContext context)
  39.     {
  40.         return DateTime.Now.ToString();
  41.     }
  42. }

  43. SqlCacheDependency
复制代码
页的Sql缓存
  1. Cahce/SqlCachePage.aspx
  2. <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="SqlCachePage.aspx.cs"
  3.     Inherits="Cahce_SqlCachePage" Title="页的Sql缓存" %>

  4. <%@ OutputCache Duration="999999" SqlDependency="VS2005_Test:sqlcache" VaryByParam="none" %>
  5. <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  6.     <p>
  7.         Duration="999999" SqlDependency="VS2005_Test:sqlcache" VaryByParam="none"<br />
  8.         如果是SqlServer2005则改成SqlDependency="CommandNotification<br />
  9.         注意配置文件中的配置
  10.     </p>
  11.     <p>
  12.         <%=DateTime.Now %>
  13.     </p>
  14. </asp:Content>

  15. 数据源控件的Sql缓存
  16. Cahce/SqlCachePage.aspx
  17. <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="SqlCacheDataSourceControl.aspx.cs"
  18.     Inherits="Cahce_SqlCacheDataSourceControl" Title="数据源控件的Sql缓存" %>

  19. <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  20.     <p>
  21.         DataSource控件设置如下属性:EnableCaching="True" SqlCacheDependency="VS2005_Test:sqlcache"
  22.         CacheDuration="Infinite"<br />
  23.         如果是SqlServer2005则改成SqlDependency="CommandNotification<br />
  24.         注意配置文件中的配置
  25.     </p>
  26.     <p>
  27.         <%=DateTime.Now %>
  28.     </p>
  29.     <p>
  30.         <asp:SqlDataSource ID="SqlDataSource1" runat="server" EnableCaching="True" SqlCacheDependency="VS2005_Test:sqlcache"
  31.             CacheDuration="Infinite" ConnectionString="<%$ ConnectionStrings:SqlConnectionString %>"
  32.             SelectCommand="SELECT * FROM [SqlCache]"></asp:SqlDataSource>
  33.         <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AllowSorting="True">
  34.         </asp:GridView>
  35.     </p>
  36. </asp:Content>

  37. web.config中的相关配置
  38.   <connectionStrings>
  39.     <add name="SqlConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\VS2005_Test.mdf;Integrated Security=True;User Instance=True"
  40.       providerName="System.Data.SqlClient" />
  41.   </connectionStrings>
  42.   <system.web>
  43.     <caching>
  44.       <sqlCacheDependency enabled="true" pollTime="10000">
  45.         <databases>
  46.           <add name="VS2005_Test" connectionStringName="SqlConnectionString" />
  47.         </databases>
  48.       </sqlCacheDependency>
  49.       <!-- 如果是SqlServer2005的话,则只需如下设置,因为SqlServer支持基于通知的缓存失效
  50.       <sqlCacheDependency enabled="true" />
  51.       -->
  52.     </caching>
  53.   </system.web>
复制代码
注意
Sql Server 2005 基于通知的缓存失效,不用aspnet_regsql设置,要设置属性SqlDependency="CommandNotification"。在首次执行某 SQL 查询之前,必须在应用程序某处调用 System.Data.SqlClient.SqlDependency.Start() 方法。此方法应放在 global.asax 文件的 Application_Start() 事件中。因为Sql Server 2005 基于通知的缓存失效对支持查询通知的查询语法有许多限制,所以我觉得最好先别用,而是使用轮询机制。在使用轮询机制时如本例子中的SqlCacheDependency="VS2005_Test:sqlcache",冒号前面是配置文件中配置的相关值指向数据库连接,后面是启用SqlCache的表名,注意区分大小写。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP