自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

詳解ASP.NET緩存的工作原理

開發(fā) 后端
本文將從ASP.NET緩存講起,從緩存的定義,工作原理開始,一直到緩存優(yōu)先級等等內(nèi)容。

這里我們將介紹ASP.NET緩存的工作原理,包括簡單的定義,數(shù)據(jù)緩存以及緩存的設(shè)置等等內(nèi)容。希望本文能對大家今后的工作有所幫助。

[[6772]]

#T#

介紹

緩存是在內(nèi)存存儲數(shù)據(jù)的一項技術(shù),也是ASP.NET中提供的重要特性之一。例如你可以在復(fù)雜查詢的時候緩存數(shù)據(jù),這樣后來的請求就不需要從數(shù)據(jù)庫中取數(shù)據(jù),而是直接從緩存中獲取。通過使用緩存可以提高應(yīng)用程序的性能。

主要有兩種類型的緩存:

1.輸出緩存Output caching

2.數(shù)據(jù)緩存Data caching

1. 輸出緩存(Output Caching)

使用輸出緩存,你可以緩存最后輸出的HTML頁面,當(dāng)相同的頁面再次請求的時候,ASP.NET不會再執(zhí)行頁面的生命周期和相關(guān)代碼而是直接使用緩存的頁面,語法如下:

  1. <%@ OutputCache Duration=”60” VaryByParam=”None”  %>  

Duration 屬性設(shè)置頁面將被緩存60妙。任何的用戶請求都會被緩存,在緩沖的60秒內(nèi)相同的請求都會直接使用緩存的頁面。當(dāng)緩存過期后ASP.NET會再次執(zhí)行頁面代碼并且為下一個60秒創(chuàng)建一個新的HTML緩存。

  1.  <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" 
  2.         CodeFile="OutputCachingTest.aspx.cs" Inherits="OutputCachingTest" Title="Untitled Page" %> 
  3.  <%@ OutputCache Duration="20" VaryByParam="None" %> 
  4.  <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">   
  5.    <div class="title">Output Cache</div> 
  6.    Date: <asp:Label ID="lblDate" runat="server" Text="" /> 
  7.    Time: <asp:Label ID="lblTime" runat="server" Text="" />         
  8.  </asp:Content> 
  9. protected void Page_Load(object sender, EventArgs e)  
  10. {  
  11.    lblDate.Text = DateTime.Now.ToShortDateString();  
  12.    lblTime.Text = DateTime.Now.ToLongTimeString();   
  13. }  

在這個例子中頁面將被緩存20秒。

通過查詢字符串緩存(Cache by Query String )
在實際應(yīng)用中頁面往往會根據(jù)一些參數(shù)動態(tài)的改變頁面的內(nèi)容。如果你的頁面是通過查詢字符串來獲取信息的,你可以根據(jù)查詢字符串很容易的緩存頁面的不同拷貝。VarByParam=”None”指定ASP.NET只存儲緩存頁面的一個拷貝。VarByParam=”*” 指定ASP.NET根據(jù)不同的查詢字符串存儲不同的緩存頁面。

  1. <%@ OutputCache Duration="60" VaryByParam="*" %> 
  2.  
  3. <div align="right"> 
  4.    <a href="OutputCachingTest2.aspx">No Query String</a> |   
  5.    <a href="OutputCachingTest2.aspx?id=1">ID 1</a> |   
  6.    <a href="OutputCachingTest2.aspx?id=2">ID 2</a> |   
  7.    <a href="OutputCachingTest2.aspx?id=3">ID 3</a> |  
  8.    <a href="OutputCachingTest2.aspx?id=3&langid=1">ID 3</a> 
  9. </div>  

上面的例子中,在查詢字符串中傳了不同的ID.ASP.NET為每一個ID都存儲了單獨的緩存頁面。這種方式會有一些問題就是當(dāng)查詢字符串范圍很廣的時候。這個時候我們可以在VarByParam 屬性中指定重要的查詢字符串變量的名字,如下:

  1. <%@OutputCacheDuration="60"VaryByParam="id;langid"%>  

這樣,ASP.NET可以根據(jù)id” or “l(fā)angid”來緩存不同的緩存版本。

自定義緩存(Custom Caching)

你也可以創(chuàng)建自定義的程序來緩存頁面。ASP.NET提供了一種很便捷的方式來創(chuàng)建自定義緩存,使用VarByCustom屬性指定自定義緩存類型的名字。

  1. %@OutputCacheDuration="20"VaryByParam="None"VaryByCustom="browser"

你還要創(chuàng)建為緩存生成自定義字符串的方法,如下:

  1. public override stringGetVaryByCustomString(HttpContext context, stringcustom)  
  2. {  
  3.     if(custom == "browser")  
  4.     {  
  5.        returncontext.Request.Browser.Browser +  
  6.               context.Request.Browser.MajorVersion;  
  7.     }  
  8.     else 
  9.    {  
  10.        return base.GetVaryByCustomString(context, custom);  
  11.     }  
  12. }  

這個方法必須寫在global.asax文件中。ASP.NET使用該方法返回的字符串來實現(xiàn)緩存,如果這個方法在不同的請求中返回相同的字符串,ASP.NET就會使用緩存的頁面,否則就會生成新的緩存版本。

上面的例子中GetVaryByCustomString()方法根據(jù)瀏覽器的名字創(chuàng)建緩存字符串,ASP.NET會根據(jù)不同的瀏覽器請求創(chuàng)建不同版本的緩存。

控件緩存(Control Cache )
上面的緩存技術(shù)可以讓你很容易的緩存整個頁面,如果要緩存指定控件的內(nèi)容,可以通過指定VaryByControl 屬性來完成。

  1. <%@OutputCacheDuration="20"VaryByControl="MyControl_1"%> 

上面代碼ASP.NET將會緩存MyControl_1控件20分鐘。如果要根據(jù)一些屬性值來緩存控件只需要將OutPutCache指令加入*.ascx頁面。 

  1. <%@Control Language="C#"AutoEventWireup="true"CodeFile="MyControl.ascx.cs"Inherits="Controls_MyControl"%> 
  2. <%@OutputCacheDuration="20"VaryByControl="EmployeeID"%> 
  3. ......  
  4. ......  

VaryByControl=”EmployeeID”告訴ASP.NET根據(jù)控件中聲明的EmployeeID屬性來創(chuàng)建不同版本的緩存。

在 .ascx.cs 文件加入EmplyeeID屬性為ASP.NET 緩存使用。

  1. private int_employeeID;  
  2. public intEmployeeID  
  3. {  
  4.    get{ return_employeeID; }  
  5.    set{ _employeeID = value; }  
  6. }  
  7.  
  8. protected voidPage_Load(objectsender, EventArgs e)  
  9. {  
  10.    lblDate.Text = DateTime.Now.ToShortDateString();  
  11.    lblTime.Text = DateTime.Now.ToLongTimeString();  
  12.  
  13.    lblEmployeeID.Text = EmployeeID.ToString();  
  14.  

在頁面中增加控件并且設(shè)置 EmployeeID.

  1. <%@RegisterSrc="Controls/MyControl.ascx"TagName="MyControl"TagPrefix="uc1"%> 
  2. <asp:ContentIDasp:ContentID="Content1"ContentPlaceHolderID="ContentPlaceHolder1"runat="Server"> 
  3.     <divaligndivalign="center"> 
  4.         <uc1:MyControlIDuc1:MyControlID="MyControl1"runat="server"EmployeeID="1"></uc1:MyControl> 
  5.     </div> 
  6. </asp:Content> 

緩存配置文件(Cache Profile )
web.config可以配置緩存相關(guān)的設(shè)置,

  1. <system.web> 
  2.   <caching> 
  3.     <outputCacheSettings> 
  4.       <outputCacheProfiles> 
  5.      <addnameaddname="ProductItemCacheProfile" duration="60"/> 
  6.    </outputCacheProfiles> 
  7. </outputCacheSettings> 
  8.    </caching> 
  9. </system.web> 

你可以通過設(shè)置 CacheProfile=”ProfileName” 屬性 來使用上面的配置:

  1. %@OutputCacheCacheProfile="ProductItemCacheProfile"VaryByParam="None"% 

2. 數(shù)據(jù)緩存(Data Caching)

ASP.NET還提供了另一種靈活的緩存類型:數(shù)據(jù)緩存。你可以將一些耗費時間的條目加入到一個對象緩存集合中,以鍵值的方式存儲。

Cache["Name"] = data;

我們可以通過使用Cache.Insert()方法來設(shè)置緩存的過期,優(yōu)先級,依賴項等。

  1. date1 = DateTime.Now;  
  2. Cache.Insert("Date1", date1, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero); 

ASP.NET允許你設(shè)置一個絕對過期時間或滑動過期時間,但不能同時使用。

緩存依賴項Cache dependency

緩存依賴項使緩存依賴于其他資源,當(dāng)依賴項更改時,緩存條目項將自動從緩存中移除。緩存依賴項可以是應(yīng)用程序的 Cache 中的文件、目錄或與其他對象的鍵。如果文件或目錄更改,緩存就會過期。

  1. date2 = DateTime.Now;  
  2. string[] cacheKeys = { "Date1"};  
  3. CacheDependency cacheDepn = newCacheDependency(null, cacheKeys);  
  4. Cache.Insert("Date2", date2, cacheDepn); 

上面的例子“Date2”緩存對象依賴“Date1”緩存條目,當(dāng) “Date1” 對象過期后“Date2” 將會自動過期。CacheDependency(null, cacheKeys)中的第一個參數(shù)為空是由于我們只監(jiān)視緩存鍵的更改情況。

回調(diào)函數(shù)和緩存優(yōu)先級(Callback Method and Cache Priority)

ASP.NET允許我們寫一個回調(diào)函數(shù),當(dāng)緩存條目從緩存中移除的時候觸發(fā)。還可以設(shè)置緩存條目的優(yōu)先級。

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.   DateTime? date1 = (DateTime?)Cache["Date1"];  
  4.   if (!date1.HasValue) // date1 == null  
  5.   {  
  6.     date1 = DateTime.Now;  
  7.     Cache.Insert("Date1", date1, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero,   
  8.                  CacheItemPriority.Default, new CacheItemRemovedCallback(CachedItemRemoveCallBack));  
  9.   }  
  10.  
  11.   DateTime? date2 = (DateTime?)Cache["Date2"];  
  12.   if (!date2.HasValue) // date2 == null  
  13.   {  
  14.     date2 = DateTime.Now;  
  15.     Cache.Insert("Date2", date2, null, DateTime.Now.AddSeconds(40), TimeSpan.Zero,   
  16.                  CacheItemPriority.Default, new CacheItemRemovedCallback(CachedItemRemoveCallBack));  
  17.   }  
  18.  
  19.   // Set values in labels  
  20.   lblDate.Text = date1.Value.ToShortDateString();  
  21.   lblTime.Text = date1.Value.ToLongTimeString();  
  22.  
  23.   lblDate1.Text = date2.Value.ToShortDateString();  
  24.   lblTime1.Text = date2.Value.ToLongTimeString();  
  25.  
  26. }  
  27.      
  28. private void CachedItemRemoveCallBack(string key, object value, CacheItemRemovedReason reason)  
  29. {  
  30.   if (key == "Date1" || key == "Date2")  
  31.   {   
  32.      Cache.Remove("Date1");  
  33.      Cache.Remove("Date2");  
  34.   }  

例子中創(chuàng)建了“Date1” 和 “Date2”緩存?!癉ate1” 在20秒后過期“Date2”為40秒。但是由于我們注冊了移除的回調(diào)函數(shù),當(dāng)“Date1” 或 “Date2”其中一個過期都會執(zhí)行CachedItemRemoveCallBack 方法,在這個方法中移除了兩個緩存條目,ASP.NET還提供了處理緩存條目更新時的回調(diào)函數(shù)CacheItemUpdateCallback 。

原文標(biāo)題:ASP.NET緩存

鏈接:http://www.cnblogs.com/carysun/archive/2009/11/08/AspDotNetCache.html

責(zé)任編輯:彭凡 來源: 博客園
相關(guān)推薦

2009-08-03 12:40:46

ASP.NET編程模型

2009-07-31 10:23:44

緩存頁面ASP.NET緩存

2009-07-29 16:08:07

ASP和ASP.NET

2009-07-29 15:34:13

2009-07-28 16:57:50

ASP.NET Ses

2009-07-24 10:14:22

ASP.NET開發(fā)

2009-08-05 11:14:33

ASP.NET ISA

2009-07-22 16:25:41

ASP.NET AJA

2009-07-23 13:19:51

2009-08-04 15:22:33

ASP.NET緩存機制

2009-07-29 14:35:34

頁面輸出緩存ASP.NET

2009-07-31 10:33:54

ASP.NET頁面輸出

2009-07-29 10:35:51

ASP.NET緩存

2009-07-28 13:02:28

asp.net

2009-03-31 09:18:34

客戶端內(nèi)置對象ASP.NET

2009-07-23 13:09:23

2009-07-28 13:39:44

加載ViewStateASP.NET

2009-08-04 10:43:59

ASP.NET控件開發(fā)

2009-08-19 13:44:00

ASP.NET Lis

2009-08-04 18:10:35

ASP.NET動態(tài)編譯
點贊
收藏

51CTO技術(shù)棧公眾號