自己整理的asp.net 缓存 相关资料

 

缓存
缓存机制
页输出缓存:保存页处理输出,下次重用所保存的输出
应用程序缓存:允许缓存所生成的数据,如DataSet

㈠页输出缓存

1、页输出缓存的几中形式
①<%@ OutputCache Duration="60" VaryByParam="None" Location="Any"%>
Location指定在哪个地方缓存,Any任何地方都缓存。
60秒以内看到的都是一样的了。
②还可在配置文件里写,然后在页面调用配置文件的缓存名称。
③用编程的方式:
Response.Canche.SetExpires(DateTime.Now.AddSeconds(3));
Response.Canche.SetCacheabiliy(HttpCacheability.Public);
Response.Canche.SetValidUntilExpires(true);
相当于:
Public => Any
Private => Client
NoCache => None
Server => Server
ServerAndPrivate =>ServerAndClient

2、使用文件依赖项缓存页输出
产生背景:有时候,可能需要在文件发生更改时从输出缓存中移除某一项。就是说文件改了以后缓存立即失效。
string filepath = Server.MapPath("TextFile1.txt");
Response.AddFileDependency(filepath);//添加缓存依赖项
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntiExpires(true);

3、缓存多个版本
①使用请求的浏览器对页的各个版本进行缓存
<%@OutputCache Duration="10" VaryByParam="None" VaryByCustom="browser"%>
②使用参数对页的各个版本进行缓存
<%@OutputCache Duration="60" VaryByParam="City"%>
这个调试可以在url后加QueryString
如:...url?City=shanghai
程序里得到这个上海然后再做其他的操作,这个时候如果参数传的还是shanghai它就不会在走到程序里了。

4、动态更新缓存页的部分,有三种方法可以实现部分不缓存
①已声明方式使用Substitution控件
<asp:Substitution ID="Substitution1" runat="server" MethodName="GetCurrentDateTime" />
public static string GetCurrentDateTime(HttpContext context)
{
return DateTime.Now.ToString();
}
//方法签名必须和委托签名一致
②以编程的方式使用Substitution控件API
Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetCurrentDateTime))
③以隐式方式使用AdRotator控件
这个控件永远都是不缓存的

㈡SQL Server依赖的缓存,非常之有用
当表数据发生改变就清除缓存

1、为SQL Server启用缓存通知
aspnet_regsql.exe -S <Server> -U <Username> -P <Password>
-ed -d Northwind -et -t Employees
Server:服务器
Username:用户名
Password:密码
Northwind:数据库
Employees:表
2、为缓存功能配置网页
<%@OutputCache Duration="3600" SqlDependency="Northind:Employees" VaryByParam="none"%>
3、在Web.config文件中设置缓存配置
<caching>
 <sqlCacheDependency enabled="true" pollTime="1000">
  <database>
   <add name="Northind" connectionStringName="..." pollTime = "1000" />
   </database>
 </sqlCacheDependency>
</caching>
//这里的name要是数据库名称

posted @ 2008-03-07 11:16  快乐就好  阅读(276)  评论(0编辑  收藏  举报