如何使用 @ OutputCache 指令的 VaryByCustom 属性来缓存不同版本的页面(二)

本文详细介绍了PetShop网站中如何使用VaryByCustom属性来管理不同条件下的输出缓存,特别是针对Category页面的大数据量访问场景。通过自定义GetVaryByCustomString方法实现了根据不同类别和用户认证状态变化缓存策略。

petshop输出缓存设置
petshop
web页面上部的ControlHeader是随着用户登陆的状态有关的,故其设置了VaryByCustom属性以来标识用户不同登陆状态的缓存版本。而Category页面由于可能被大量的访问,并且数据量很大,是十分有必要缓存的,但是由于数据的随机性很大,存在不同的版本,比如说是不同类别的Category,甚至不同的分页显示的数据页,在这里采用了VaryByCustom属性以缓存不同版本的页。

我们再看下其具体实现代码:
VaryByCustom,我们可以自定义输出缓存要求的任意文本。除了在OutputCache指令里面申明该属性之外,我们还得在应用程序的 global.asax 文件的代码声明块中,重写 GetVaryByCustomString 方法来为自定义字符串指定输出缓存的行为。

举一列来说:

<%@ OutputCache VaryByParam="none" VaryByCustom="CategoryPageKey" Location="server" Duration="43200" %>

这里的VaryByCustom定义的为CategoryPageKey,那么在global.asax里面我们必须定义CategoryPageKey这个字符创输出缓存的行为,见下面代码。

public override string GetVaryByCustomString(HttpContext context, String arg) {

string cacheKey = "";

switch(arg) {

case "CategoryPageKey":

if (Request.IsAuthenticated == true) {

cacheKey = "QQQ" + context.Request.QueryString["category_id"] + context.Request.QueryString["requestedPage"];

}

else {

cacheKey = "AAA" + context.Request.QueryString["category_id"] + context.Request.QueryString["requestedPage"];

}

break;

case "SearchPageKey" :

if (Request.IsAuthenticated == true) {

cacheKey = "QQQ" + context.Request.QueryString["search_text"] + context.Request.QueryString["requestedPage"];

}

else {

cacheKey = "AAA" + context.Request.QueryString["search_text"] + context.Request.QueryString["requestedPage"];

}

break;

case "ProductPageKey" :

if (Request.IsAuthenticated == true) {

cacheKey = "QQQ" + context.Request.QueryString["name"] + context.Request.QueryString["product_id"] + context.Request.QueryString["requestedPage"];

}

else {

cacheKey = "AAA" + context.Request.QueryString["name"] + context.Request.QueryString["product_id"] + context.Request.QueryString["requestedPage"];

}

break;

case "ProductDetailsPageKey" :

if (Request.IsAuthenticated == true) {

cacheKey = "QQQ" + context.Request.QueryString["item_id"] + context.Request.QueryString["requestedPage"];

}

else {

cacheKey = "AAA" + context.Request.QueryString["item_id"] + context.Request.QueryString["requestedPage"];

}

break;

case "UserID" :

if (Request.IsAuthenticated == true) {

cacheKey = "UserID_In";

}

else {

cacheKey = "UserID_Out";

}

break;

}

return cacheKey;

}

从上面对CategoryPageKey字符创所作的行为来看,当我们的请求页面中含有对特定的category_id的某一分页显示的数据页的请求时,将调用缓存(自然是已经缓存了该页)。

转载于:https://www.cnblogs.com/leonjoon/archive/2006/08/27/487747.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值