缓存之整页缓存 进阶

来源:互联网 发布:掌上贵金属软件下载 编辑:程序博客网 时间:2024/04/30 08:50

介绍

  整页缓存主要有 Duration 、VaryByParam 和VaryByParam等属性
        

        1.Duration

        该属性是必须的,属性值以秒为单位的正整数,表示页面从请求开始,持续缓存的事件。
页面在第一次请求时,运行并缓存其输出对于在缓存时间内的后续请求将通过缓存来完成,页
面代码不会被执行
        

        2.VaryByParam

        在ASP.NET中,一个页面可以根据传入参数的不同显示不同的结果。以商品查询系统为例,
商品详情页会接受一个商品的编号,
        根据编号不同显示不同商品信息 ,其URL地址如“detail.aspx?id=1”等每个商品的信息都是
相对固定的,可以设置整页缓存
        
        商品详情页面被缓存了1200秒,当VaryByParam属性设置为“none”,此时页面输出缓存忽
略URL地址中查询的字符串,
        所以即使传入的参数不同,详情页面也只缓存一个结果,通过设置VaryByParam属为“id” 
        
        如果传递的参数很多个,可以用分号分隔每个参数
        VaryByParam="name;id"  
        如果希望通过所有参数来缓存页面  则将属性设置为星号“*”


      3.VarByControl

        在实际项目中,经常要实现根据用户的选择来筛选数据的功能,如根据部门查询对应的员工。
        如果筛选的数据相对固定,为了提高性能,则需要使用整页缓存的技术
        
        当用户请求访问页面时,该页面将会缓存在服务器内存中,持续时间为120秒。
        在缓存的有效时间内,再次访问页面时,即使选择了其他部门时,显示仍是要查看的员工
        通过设置 OutputCache指令的VaryByControl属性是DropDownList的id值,即可解决该问题,

代码示例



//跳转页面
<form id="form1" runat="server">        <div>            <a href="T2-1.aspx?id=1">1</a>            <a href="T2-1.aspx?id=2">2</a>        </div>    </form>

//跳转后台代码
namespace ch6{    public partial class T2_1 : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                Response.Write("商品" + Request["id"]);            }        }    }}

   <form id="form1" runat="server">    <div>        </div>    </form>

缓存设置
<%@ OutputCache Duration="11111" VaryByParam="id" %>

代码实例2


<form id="form1" runat="server">        <asp:DropDownList ID="DropDownList1" runat="server" Height="16px" AutoPostBack="True" OnTextChanged="DropDownList1_TextChanged">            <asp:ListItem Value="0">1</asp:ListItem>            <asp:ListItem Value="1">2</asp:ListItem>            <asp:ListItem Value="2">3</asp:ListItem>            <asp:ListItem Value="3">4</asp:ListItem>            <asp:ListItem Value="4">5</asp:ListItem>        </asp:DropDownList>        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>    </form>


<%@ OutputCache Duration="120"  VaryByParam="none" VaryByControl="DropDownList1" %>




0 0