ASP.NET 页缓存

[ 2006-09-03 19:20:29 | 作者: yuhen ]
字号: | |
使用页缓存可大大提高系统的性能,ASP.NET 的页缓存由 OutputCacheModule 控制。OutputCacheModule 会根据相关环境参数来决定输出结果,也正因为这样在缓存有效期内不会调用页方法和事件。另外页缓存(System.Web.HttpCachePolicy)和程序缓存(System.Web.Caching.Cache)并不是一回事。

1. AddValidationCallback

OutputCacheModule 会在每次请求时回调 HttpCacheValidateHandler,因此我们可以通过 HttpCachePolicy.AddValidationCallback() 方法来进行一些针对缓存的操作。

如下面的例子中,当请求带有 "cache=0" 参数时修改验证状态,直接执行当前请求,而不是从缓存输出。(修改验证状态仅对当前请求有效,并不会影响整个缓存策略。)
this.Response.Cache.AddValidationCallback(
    delegate(HttpContext context, Object data, ref HttpValidationStatus status)
    {
        if (HttpContext.Current.Request.QueryString["cache"] == "0")
        {
            HttpContext.Current.Response.Write("Executing...<br>");
            status = HttpValidationStatus.Invalid;
        }
    }, null);

HttpCacheValidateHandler 由 OutputCacheModule 调用,因此我们不能直接使用 "this.Response",而必须改用 "HttpContext.Current.Response" 。

2. 刷新缓存

通过缓存依赖,我们可以很方便地让让缓存失效。

在下面的例子中,我们添加了一个 CacheItemDependency,只要调用 RefreshCache 方法删除依赖项,就会为新请求重新缓存页面输出结果。
private const string cacheItem = "Cache1";

protected void Page_Load(object sender, EventArgs e)
{
    this.Response.Write(DateTime.Now.ToString());
    
    this.Cache.Insert(cacheItem, new object());
    this.Response.AddCacheItemDependency(cacheItem);
}

public static void RefreshCache()
{
    HttpContext.Current.Cache.Remove(cacheItem);
}            

结合前面的例子,我们可以使用 AddValidationCallback 注册一个回调,当请求有特定参数时执行 RefreshCache() 刷新缓存。

3. HttpCacheability

MSDN 文档对于 HttpCacheability 的解释有些模糊,我查了一些资料,希望能让大家更明白点。

NoCache: 仅在共享缓存设备(代理服务器)有条件缓存,且该缓存需要经服务器验证才能发给客户端。
Private: 仅在客户端缓存。单击浏览器前进/后退按钮时有用,刷新浏览器(F5)时依然向服务器发出请求。
Public: 在客户端、共享缓存设备(代理服务器)和服务器都进行缓存。
Server: 仅在服务器缓存。
ServerAndNoCache: 仅在服务器和共享缓存设备(代理服务器)进行缓存。
ServerAndPrivate: 仅在服务器和客户端缓存。
[最后修改由 yuhen, 于 2006-09-04 02:10:44]
评论Feed 评论Feed: http://www.rainsts.net/feed.asp?q=comment&id=312

这篇日志没有评论。

发表评论
表情图标
[smile] [confused] [cool] [cry]
[eek] [angry] [wink] [sweat]
[lol] [stun] [razz] [redface]
[rolleyes] [sad] [yes] [no]
[heart] [star] [music] [idea]
UBB代码
转换链接
表情图标
悄悄话
用户名:   密码:  
验证码 * 请输入验证码