1、OutputCache输出缓存
语法:<%@ OutputCache Duration="60" VaryByParam="CategoryID"%>
Duration缓存间隔时间 单位秒
VaryByParam参数 可以为none(无)
例: <SelectParameters>
<asp:QueryStringParameter Name="CategoryID" QueryStringField="CategoryID"
Type="Int32" DefaultValue="1" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:HyperLink ID="HyperLink1" runat="server" Height="20px"
NavigateUrl="~/Default.aspx?CategoryID=1" Width="20px">1</asp:HyperLink>
用VaryByParam配合sql查询语句使用CategoryID来筛选表格中的内容
回调缓存,是一个页面大部分都是静态的情况,而需要一小部分是动态的,这时候就需要回调缓存,
回调缓存需要定义一个方法在后置文件中,例:
public static string GetHttp(HttpContext context)
{
return DateTime.Now.ToString();
}
在源代码中:
(1) time:<%=DateTime.Now.ToString() %>
(2)<%Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetHttp));%>
(1)中的时间在第一次访问时,加入到OutCache的,在缓存周期时间里,刷新不会得到新的时间,而(2)在相同页面上调用回调缓存,每次刷新都是新的时间
另外还有一种方法叫Page Fragment Caching,它是将需要缓存的数据做成用户自定义控件,将OutCache写在用户自定义控件中,把自定义控件放入一个新的页面,在这新的页面中不定义outCache,那么只有自定义控件会被放到OutCache,而此页面中其它控件都不会被放入OutCache
2、DataCache 数据缓存
数据缓存是将数据放到缓存区,在每次访问时,如果Cache中有指定的Source那么就将Cache中的Source邦定到GridView中,否则就新建立数据存入Cache,例如下:
DataView Source;
Source = (DataView)Cache["MyDataSet"];
if(Source == null)
{SqlConnection thisSqlConnection = new SqlConnection(@"server = localhost;Integrated Security = true;" + "Database=northwind");
SqlDataAdapter thisDataAdapter = new SqlDataAdapter("SELECT ProductName,CategoryID FROM Products", thisSqlConnection);
//SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisDataAdapter);
DataSet thisSet = new DataSet();
thisDataAdapter.Fill(thisSet, "Products");
thisSqlConnection.Close();
Source = new DataView(thisSet.Tables["Products"]);
Cache["MyTables"] = Source;
}
GridView1.DataSource = (object)Source;
GridView1.DataBind();
3、SQL Cache SQL缓存
(a)打开dos 在vs目录下会有一个aspnet_regsql.exe工具
(1)aspnet_regsql.exe -S "localhost" -E -d "Northwind" -ed //为SQL缓存依赖项启用该数据库
(2)aspnet_regsql.exe -S "localhost" -E -d "Northwind" -et -t "Products" //为SQL缓存依赖项启用该表
(b) 打开web.config
<caching>
<sqlCacheDependency enabled="true" pollTime="1000" >//多久检查一次数据看是否更改
<databases>
<add name="Northwind" connectionStringName="NorthwindConnectionString" />//Northwind为数据库, 后面是数据库连接字符串名
</databases>
</sqlCacheDependency>
</caching>
(c)设置所使用该库和表的源文件
SqlDependency="Northwind:Products“//库和表之间用:连接
<%@ OutputCache Duration="999999" SqlDependency="Northwind:Products" VaryByParam="none" %>
也可以在数据库控件上指定<asp:SqlDataSource EnableCaching="true" CacheDuration="Infinite" SqlCacheDependency="Northwind:Products" ... />