數據緩存技術及代碼詳解


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

 

  轉載請注明出處:http://www.cnblogs.com/refactor

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM