1. 程式人生 > >資料快取技術及程式碼詳解

資料快取技術及程式碼詳解

1.快取概述
  •為什麼使用快取
    – 應用程式可以將那些頻繁訪問的資料,以及那些需要大量處理時間來建立的資料儲存在記憶體中,從而提高效能
  • 快取機制分類介紹
    – 應用程式快取
    – 頁輸出快取

2.應用程式快取的機制
  • 應用程式快取是由System.Web.Caching.Cache 類實現的,快取例項(Cache 物件)是每個應用程式專
    用的,並且每個應用只有一個,通過Page類或UserControl類的Cache 屬性公開
   • 快取生存期依賴於應用程式的生存期,當重新啟動應用程式後,將重新建立Cache 物件,也就是說快取資料將被清空

3.如何將項新增到快取中 
  • 新增快取項
  • 設定快取依賴項  
  • 設定快取過期策略
  • 設定快取優先順序
4.設定快取依賴項
  • 為什麼要設定依賴項
  • 依賴項分類
    – 鍵依賴項
    – 檔案依賴項
    –SQL 依賴項
    – 聚合依賴項
    – 自定義依賴項
  • 新增快取項的檔案依賴項
    Cache.Insert("FinanceData", "Cached Item 4",
      new System Web Caching CacheDependency(Server.MapPath( "XMLData.xml " ))); 
  • 新增快取項的SQL 依賴項
    – 使用SqlCacheDependency 物件來建立依賴於資料庫表中的記錄
    – 在Web.config 檔案的caching節點定義快取使用的資料庫名稱及連線字串
    – 使用程式碼依賴於該連線對應資料庫的某個表的快取項
      Cache.Insert("cacheitem1", "Cache Item 1",
        new SqlCacheDependency("AdvWorks", "Product"));
5.從快取中刪除項時通知應用程式
  • CacheItemRemovedCallback 委託
    – 該委託定義編寫事件處理程式時使用的簽名,當對從快取中刪除項進行響應時會呼叫此事件處理程式
  • CacheItemRemovedReason 列舉
    – 用於指定刪除快取項的原因

6.例項演示(使用CacheDependency監視檔案變化)

  a)新建一個CacheUtil類,來處理Cache的常見操作,程式碼如下: 

View Code
    public class CacheUtil
    {
        public static void AddCache()
        {
            var ds = new System.Data.DataSet();
            ds.ReadXml(HttpContext.Current.Server.MapPath("~/Employees.xml"));

            HttpContext.Current.Cache.Add(
"EmployeeSet", ds, new CacheDependency(HttpContext.Current.Server.MapPath("~/Employees.xml")) , DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.High , EmployeeSetCacheItemRemoved); } public static void EmployeeSetCacheItemRemoved(string
key, object value, CacheItemRemovedReason reason) { switch (reason) { case CacheItemRemovedReason.DependencyChanged: AddCache(); break; } } }

   b)修改Global.asax.cs的Application_Start,在網站啟動時,新增Cache

View Code
        void Application_Start(object sender, EventArgs e)
        {
            //在應用程式啟動時執行的程式碼
            CacheUtil.AddCache();
        }

  c)修改Default.aspx.cs的Page_Load

View Code
  protected void Page_Load(object sender, EventArgs e)
        {
            if (Cache["EmployeeSet"] == null)
            {
                CacheUtil.AddCache();
            }
            var ds = (DataSet)Cache["EmployeeSet"];
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
        }

   d)效果圖:

  當修改Employees.xml,儲存後,快取會接到檔案改變通知,重新載入資料

7.例項演示(使用SqlCacheDependency監視資料庫表變化)

  a)新建一個頁面SqlCacheTest.aspx,使用模板頁

  b)啟用資料庫快取依賴項

  此時會在資料庫Student中的表Contact生成一個觸發器和一堆儲存過程:

  c)配置web.Config

    在  <system.web>節點下,加入:

View Code
    <caching>
      <sqlCacheDependency enabled="true">
        <databases>
          <add name="Student" connectionStringName="Student"/>
        </databases>
      </sqlCacheDependency>
    </caching>

    設定connectionStringName:

View Code
<connectionStrings>
    <add name="Student"
         connectionString="server=.;database=Student;Integrated Security=SSPI"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

  d)修改CacheUtil.cs

View Code
    public class CacheUtil
    {
        public static void AddCache()
        {
            var ds = new DataSet();
            ds.ReadXml(HttpContext.Current.Server.MapPath("~/Employees.xml"));
            
            HttpContext.Current.Cache.Add("EmployeeSet", ds, new CacheDependency(HttpContext.Current.Server.MapPath("~/Employees.xml"))
                ,DateTime.Now.AddHours(1),Cache.NoSlidingExpiration, CacheItemPriority.High
                ,EmployeeSetCacheItemRemoved);
        }

        public static void EmployeeSetCacheItemRemoved(string key, object value, CacheItemRemovedReason reason)
        {
            switch (reason)
            {
                case CacheItemRemovedReason.DependencyChanged:
                    AddCache();
                    break;
            }
        }

        public static void AddSqlCache()
        {
            var dt = new DataTable();
            var da = new SqlDataAdapter("select * from Contact", ConfigurationManager.ConnectionStrings["Student"].ConnectionString);
            da.Fill(dt);
            HttpContext.Current.Cache.Add("Contact"
                                          , dt
                                          , new SqlCacheDependency("Student", "Contact")
                                          , DateTime.Now.AddDays(1)
                                          , Cache.NoSlidingExpiration
                                          , CacheItemPriority.High
                                          , ContactCacheItemRemoved);
        }

        public static void ContactCacheItemRemoved(string key, object value, CacheItemRemovedReason reason)
        {
            switch (reason)
            {
                case CacheItemRemovedReason.DependencyChanged:
                    AddSqlCache();
                    break;
            }
        }
    }

  e)修改Global.asax.cs的Application_Start

View Code
        void Application_Start(object sender, EventArgs e)
        {
            //在應用程式啟動時執行的程式碼
            CacheUtil.AddCache();
            CacheUtil.AddSqlCache();
        }

  f)修改SqlCacheTest.aspx.cs的Page_Load

View Code
 protected void Page_Load(object sender, EventArgs e)
        {
            if (Cache["Contact"] == null)
            {
                CacheUtil.AddSqlCache();
            }
            var dt = (DataTable)Cache["Contact"];
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

  g)效果圖

  當我們在SSMS中修改資料庫表的資料後,停小段時間,重新整理頁面

8)頁輸出快取概述
  • 頁輸出快取是指在快取ASP.NET  頁所生成的部分響應或所有響應
  • 提高Web應用程式的效能
  • 提高Web伺服器的吞吐量
9)SqlCacheDependency
  • System.Web.Caching.SqlCacheDependency
  – 建立依賴於資料庫中表或行的快取項
    – <%@ OutputCache Duration="30"
      VaryByParam="none“ SqlDependency="Student:Contact" %>
10)部分頁快取
  • 控制元件快取
    – 控制元件快取(也稱為片段快取),可以通過建立 控制元件快取(也稱為片段快取),使用者控制元件來包含快取的內容,然後將使用者控制元件
      標記為可快取來快取部分頁輸出
  • 快取後替換
    – 以宣告方式使用Substitution 控制元件
    – 以程式設計方式使用Substitution 控制元件API
    – 以隱式方式使用AdRotator 控制元件
11)DataSource 快取
  • 啟用XxxDataSource 當中的快取
  • 快取單個數據源控制元件

12)SqlCacheDependency頁面輸出快取例項

  a)新建資料夾:OutputCache

  b)在資料夾OutputCache中新建SqlCacheDependency.aspx 

View Code
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SqlCacheDependency.aspx.cs" Inherits="UseCache.OutputCache.SqlCacheDependency" %>

<%@ OutputCache Duration="3600" VaryByParam="none" SqlDependency="Student:Contact" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

        <br />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <br />

</asp:Content>

  後臺程式碼:

View Code
    public partial class SqlCacheDependency : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = DateTime.Now.ToLongTimeString();
            var dt = new DataTable();
            var da = new SqlDataAdapter("select * from Contact",
                                        ConfigurationManager.ConnectionStrings["Student"].ConnectionString);
            da.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

13)使用使用者控制元件

  a)在資料夾OutputCache中新建LableControl.ascx

View Code
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="LableControl.ascx.cs" Inherits="UseCache.OutputCache.LableControl" %>
<%@ OutputCache Duration="5" VaryByParam="none" %>

 <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

  後臺程式碼:

View Code
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = DateTime.Now.ToLongTimeString();
        }

  b)在資料夾OutputCache中新建PartialCachePage.aspx

View Code
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="PartialCachePage.aspx.cs" Inherits="UseCache.OutputCache.PartialCachePage" %>
<%@ Register src="LableControl.ascx" tagname="GridControl" tagprefix="uc1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />

         LableControl使用者控制元件快取5秒:<uc1:GridControl ID="LableControl1" runat="server" />
</asp:Content>

  後臺程式碼:

View Code
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = DateTime.Now.ToLongTimeString();
        }

14)使用SqlDataSource

  在資料夾OutputCache中新建SqlDataSourceCache.aspx