缓存技术是asp.net程序设计中非常实用的技术,也是大型web程序设计中比较常见的技术。本文就以实例形式对此加以说明。具体如下:
asp.net页面的SqlCacheDependency Sql缓存:
Cahce/SqlCachePage.aspx页面代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<%@ Page Language= "C#" MasterPageFile= "~/Site.master" AutoEventWireup= "true" CodeFile= "SqlCachePage.aspx.cs" Inherits= "Cahce_SqlCachePage" Title= "页的Sql缓存" %> <%@ OutputCache Duration= "999999" SqlDependency= "VS2005_Test:sqlcache" VaryByParam= "none" %> <asp:Content ID= "Content1" ContentPlaceHolderID= "ContentPlaceHolder1" runat= "Server" > <p> Duration= "999999" SqlDependency= "VS2005_Test:sqlcache" VaryByParam= "none" <br /> 如果是SqlServer2005则改成SqlDependency="CommandNotification<br /> 注意配置文件中的配置 </p> <p> <%=DateTime.Now %> </p> </asp:Content> |
数据源控件的Sql缓存:
Cahce/SqlCachePage.aspx页面代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<%@ Page Language= "C#" MasterPageFile= "~/Site.master" AutoEventWireup= "true" CodeFile= "SqlCacheDataSourceControl.aspx.cs" Inherits= "Cahce_SqlCacheDataSourceControl" Title= "数据源控件的Sql缓存" %> <asp:Content ID= "Content1" ContentPlaceHolderID= "ContentPlaceHolder1" runat= "Server" > <p> DataSource控件设置如下属性:EnableCaching= "True" SqlCacheDependency= "VS2005_Test:sqlcache" CacheDuration= "Infinite" <br /> 如果是SqlServer2005则改成SqlDependency="CommandNotification<br /> 注意配置文件中的配置 </p> <p> <%=DateTime.Now %> </p> <p> <asp:SqlDataSource ID= "SqlDataSource1" runat= "server" EnableCaching= "True" SqlCacheDependency= "VS2005_Test:sqlcache" CacheDuration= "Infinite" ConnectionString= "<%$ ConnectionStrings:SqlConnectionString %>" SelectCommand= "SELECT * FROM [SqlCache]" ></asp:SqlDataSource> <asp:GridView ID= "GridView1" runat= "server" DataSourceID= "SqlDataSource1" AllowSorting= "True" > </asp:GridView> </p> </asp:Content> |
web.config中的相关配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<connectionStrings> <add name= "SqlConnectionString" connectionString= "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\VS2005_Test.mdf;Integrated Security=True;User Instance=True" providerName= "System.Data.SqlClient" /> </connectionStrings> <system.web> <caching> <sqlCacheDependency enabled= "true" pollTime= "10000" > <databases> <add name= "VS2005_Test" connectionStringName= "SqlConnectionString" /> </databases> </sqlCacheDependency> <!-- 如果是SqlServer2005的话,则只需如下设置,因为SqlServer支持基于通知的缓存失效 <sqlCacheDependency enabled= "true" /> --> </caching> </system.web> |
注意:对于Sql Server 2005来说,基于通知的缓存失效,不用aspnet_regsql设置,要设置属性SqlDependency="CommandNotification"。在首次执行某 SQL 查询之前,必须在应用程序某处调用 System.Data.SqlClient.SqlDependency.Start() 方法。此方法应放在 global.asax 文件的 Application_Start() 事件中。
希望本文所述的缓存技术对大家的asp.net程序设计有所帮助。