天天看点

ASP.NET---数据缓存技术

1. 数据缓存技术

  概述:     (1)缓存是一种在计算机中广泛用来提高性能的技术     (2)在 Web 应用程序的上下文中,缓存用于在 Http 请求间保留页或者数据,并在无需新创建的情况下多次使用它们    目的:节省应用程序处理时间和资源 

ASP.NET---数据缓存技术

2. @OutputCache 指令

<%@ OutputCache Duration="60" VaryByParam="none" %>
           
Duration属性表示页面或用户控件的缓存时间。
           
VaryByParam改变所要缓存输出的形参。
           

对于OutputCache指令 Duration和VaryByParam两个属性是必须的

3.HttpCachePolicy类

protected void Page_Load(object sender, EventArgs e)
        {
            //页面输出缓存时间是30秒
            Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
            //缓存过期的绝对时间
            Response.Cache.SetExpires(DateTime.Parse("09:22:00"));
            //设置页面缓存级别
            Response.Cache.SetCacheability(HttpCacheability.Public);
        }
           

4. 页面部分缓存

    4.1 页面部分缓存         (1) 缓存页面的一部分         (2)用来实现页面部分缓存的常用方法:控件缓存、缓存后替换     4.2把 @ OutputCache 指令写入用户控件文件 中

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<%@ OutputCache Duration="60" VaryByParam="none" %>
           

4.3 缓存后替换Substitution

      (1)在使用 Substitution 时,首先我们将整个页面缓存起来,然后将页面中需要动态改变内容的地方用 Substitution 控件代替即可       (2)Substitution 控件需要设置一个重要属性 MethodName ,该属性用于获取或者设置当 Substitution 控件执行时为回调而调用的方法名称

     4.3.1   回 调方法必须要符合 3 点:                方法必须被定义为静态方法                方法必须接受 HttpContext 类型的参数                方法必须返回 String 类型的值

事例:

页面中添加@ OutputCache指令

<%@ OutputCache Duration="10" VaryByParam="none" %>
           
<form id="form1" runat="server">
    <div>
        <fieldset>
            <legend>使用Substitution控件实现缓存后替换 </legend>
            <br />
            <div>
                以下时间显示,使用了Substitution控件
            </div>
            <asp:Substitution ID="SubTime" MethodName="GetTime" runat="server" />
            <hr style="color: Red" />
            <div>
                以下时间显示为页面缓存,缓存时间为10秒</div>
            <asp:Label ID="labTime" runat="server">
            </asp:Label><br />
        </fieldset>
    </div>
    </form>
           

在后台代码中添加GetTime方法,完成时间显示。

  protected void Page_Load(object sender, EventArgs e)

        {

            this.labTime.Text = DateTime.Now.ToLongTimeString();

        }

        public static string GetTime(HttpContext context)

        {

            return DateTime.Now.ToLongTimeString();

        }

5. 应用程序数据缓存

(1) 应用程序数据缓存的主要功能是在内存中存储各种与应用程序相关的对象。通常这些对象都需要耗费大量的服务器资源才能创建 (2) 应用程序数据缓存由 Cache 类实现

ASP.NET---数据缓存技术
 方法  描述
Add 将指定项添加到Cache对象,该对象具有依赖项、过期和优先级策略以及一个委托(可用于在从Cache移除插入项时通知应用程序)。
Insert 向 Cache 对象插入项。使用此方法的某一版本改写具有相同 key 参数的现有 Cache 项。
Remove 从应用程序的 Cache 对象移除指定项。

5.1 ADD方法

public Object Add(

stringkey,    //缓存的键

Objectvalue,  //要添加的缓存项

CacheDependencydependencies,  //依赖项

DateTimeabsoluteExpiration,  //设置的过期移除时间

TimeSpanslidingExpiration,  //最后一次访问时间过期时间的间隔

CacheItemPrioritypriority,  //对象的相对成本

CacheItemRemovedCallbackonRemoveCallback//移除时要调用的委托

)

           

5.2Insert方法

Insert(String, Object)
Insert(String, Object, CacheDependency)
Insert(String, Object, CacheDependency, DateTime, TimeSpan)
Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback)
           
//代码示例将有一分钟绝对过期时间的项添加到缓存中
Cache.Insert("CacheItem6", "Cached Item 6",
    null, DateTime.Now.AddMinutes(1d), 
    System.Web.Caching.Cache.NoSlidingExpiration);
           

5.3检索应用程序缓存对象

(1)从缓存中检索应用程序数据缓存对象的方法,我们通常可以使用 2 种方法:        指定键 名

            string categoryId = (string)Cache["categoryId"];

       使用 Cache 类的 Get 方法

            string categoryId = (string)Cache.Get("categoryId");

(2)应用程序缓存事例

添加按钮

ASP.NET---数据缓存技术

添加按钮事件

// Add方法
        protected void BtnCacheAdd_Click(object sender, EventArgs e)
        {
            //Add方法添加缓存
            Cache.Add("aaa", "我爱你中国", null, DateTime.Now.AddSeconds(60),
                        Cache.NoSlidingExpiration, CacheItemPriority.High, null);
        }

        //Insert方法
        protected void BtnCacheInsert_Click(object sender, EventArgs e)
        {
            //Insert方法添加缓存
            Cache.Insert("aaa", "我爱你北京", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration);
        }

        //查看缓存
        protected void Button1_Click(object sender, EventArgs e)
        {
            //查看缓存
            string cacheContext = "";
            //判断当前缓存是否过期
            if (Cache["aaa"] != null)
            {
                cacheContext = Cache["aaa"].ToString();
                //打印
                Response.Write(cacheContext);
            }
            else
            {
                Response.Write("已过期!!");
            }
        }
           

6.缓存依赖

       通过缓存依赖,可以在被依赖对象(如文件、目录、数据库表等)与缓存对象之间建立一个有效关联。当被依赖对象发生变化时,缓存对象将变得不可用,并被自动从缓存中移除。

ASP.NET---数据缓存技术

事例:

<form id="form1" runat="server">
    <div align="center">
        <asp:GridView ID="gvGoods" runat="server" BackColor="White" BorderColor="#CC9966"
            BorderStyle="None" BorderWidth="1px" CellPadding="4" Height="142px" Width="583px">
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
            <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
            <RowStyle BackColor="White" ForeColor="#330099" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
            <sortedascendingcellstyle backcolor="#FEFCEB" />
            <sortedascendingheaderstyle backcolor="#AF0101" />
            <sorteddescendingcellstyle backcolor="#F6F0C0" />
            <sorteddescendingheaderstyle backcolor="#7E0000" />
        </asp:GridView>
        品牌:<asp:TextBox ID="txtBread" runat="server"></asp:TextBox>
        型号:<asp:TextBox ID="txtType" runat="server"></asp:TextBox>
        数量:<asp:TextBox ID="txtNumber" runat="server"></asp:TextBox><br>
        <asp:Button ID="BtnAdd" runat="server" Text="添加数据" OnClick="BtnAdd_Click" />
    </div>
    </form>
           

后台事件代码如下:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //把XML数据取出作为数据源
                LoadGVGoods();
            }
        }

        protected void LoadGVGoods()
        {
            DataSet ds;
            //判断缓存是否为空
            if (Cache["XMLData"] == null)
            {
                ds = new DataSet();
                //获取XML路径
                string filePath = Server.MapPath("~/XMLFile.xml");
                //读取XML文件,并得到数据
                ds.ReadXml(filePath);
                //定义缓存依赖
                CacheDependency cd = new CacheDependency(filePath, DateTime.Now);
                //添加缓存
                Cache.Insert("XMLData", ds, cd);
            }
            else
            {
                ds = (DataSet)Cache["XMLData"];
            }
            //绑定数据源
            this.gvGoods.DataSource = ds;
            //重新绑定
            this.gvGoods.DataBind();
        }

        //添加数据到XML文件中
        protected void BtnAdd_Click(object sender, EventArgs e)
        {
            //引用System.Xml
            XmlDocument xd = new XmlDocument();
            //加载XML文件
            xd.Load(Server.MapPath("~/XMLFile.xml"));
            //创建节点
            XmlElement xe = xd.CreateElement("Item");
            xe.SetAttribute("Breed", this.txtBread.Text);
            xe.SetAttribute("Type", this.txtType.Text);
            xe.SetAttribute("Number", this.txtNumber.Text);
            //加入到XML中
            xd.DocumentElement.AppendChild(xe);
            //把添加好的数据保存回原文件
            xd.Save(Server.MapPath("~/XMLFile.xml"));
            //移除缓存
            Cache.Remove("XMLData");
            //调用LoadGVGoods
            LoadGVGoods();
        }
           

6.2实现SQL数据缓存依赖

      SQL 数据缓存依赖功能的核心是利用 SqlCacheDependency 类,在应用程序数据缓存对象与 SQL Server 数据库表,或者 SQL Server 查询 结果之间,建立一种缓存依赖关系。

//SqlCacheDependency类构造函数
//构造函数一
public SqlCacheDependency(SqlCommand sqlcmd);
//构造函数二
public SqlCacheDependency(string dbEntryName,string tableName);
           

注意事项:

    在构造 SQL 数据缓存依赖对象时,我们要注意:应用 SQL Server 2005 时,必须使用构造函数一,在 sqlcmd 中将涉及相关的 SQL 查询语句( select ),这些语句必须满足以下要求:        (1)必须定义完全限定的表名,包括表所有者的名称,如 dbo.Users        (2)必须在 Select 语名中显示指定列 名,不能 使用星号(*)通配符来选择表中的所有列 。        (3) 不能在查询语句中使用聚合函数

聚合缓存依赖

//自定义文件缓存依赖

CacheDependencydep1 = new CacheDependency(fileName);

//创建SQL数据缓存依赖,cmd是一个SqlCommand实例

SqlCacheDependencydep2 = new SqlCacheDependency(cmd);

//添加到CacheDependency对象组中

CacheDependency[]deps= new CacheDependency[]{ dep1, dep2 };

//调用Add方法,实现聚合缓存依赖

AggregateCacheDependencyaggDep= new AggregateCacheDependency();

aggDep.Add(deps);

//利用Insert方法,添加应用程序缓存对象

Cache.Insert(“key”,DateTime.Now,aggDep);
           

继续阅读