天天看點

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);
           

繼續閱讀