ASP.NET Cache__.net

來源:互聯網
上載者:User

原文地址:http://www.codeproject.com/KB/aspnet/AspDotNetCache.aspx

緩衝是在記憶體中儲存很耗時建立的資料的一項技術,也是ASP.NET一個重要特性。例如,你可以緩衝那些耗時的複雜查詢出來的資料,之後的請求不必再從資料庫中取數,直接從緩衝中取。通過緩衝,可以大大提高應該程式的效能。

主要有兩種緩衝類型:

1.輸出緩衝

2.資料緩衝


1. Output Caching(輸出緩衝)

使用輸出緩衝,可以快取頁面面最終的產生的HTML。當同一個頁面再次請求時,快取頁面起作用。ASP.NET不再執行頁面的生命週期和相關代碼。輸出緩衝的文法:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

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

Duration 屬性設定頁面將緩衝60秒,在所有使用者的請求中的第一次請求,ASP.NET執行頁面代碼,把生最終產生的HTML結果呈現給使用者,並在緩衝儲存。如果伺服器在60秒內再次接到同一個頁面的請求,ASP.NET自動發送緩衝中備份頁面給使用者。如果伺服器在緩衝到期後接到一個請求,ASP.NE執行頁面代碼並為下一個60秒建立一個新的HTML緩衝。

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

在本例中, 頁面將被緩衝20秒。


Cache by Query String (通過查詢字串緩衝)

在實際應用中,動態網頁面是根據參數改變頁面內容的。如果你的頁面是通過查詢字串來接收資訊的,你也可以很容易的根據查詢字串來快取頁面面的不同拷貝。VarByParam=”None” 告訴ASP.NET只儲存頁面的一份拷貝。VarByParam=”*”告訴ASP.NET根據不同的查詢字串儲存不同的頁面拷貝。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> 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值儲存一份拷貝,該技術在這種情況下利用的非常好,但是也存在一些問題。如果頁面接收很廣泛的查詢字串,那麼,ASP.Net針對每一個查詢字串參數緩衝一份拷貝,並且潛在的降低了重用性。這種情況下,你可以在VarByParam屬性中指定幾個比較重要的查詢參數。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

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

如上所設定,ASP.Net根據不同的“id” 或者 “langid”查詢字串值緩衝不同的版本


Custom Caching(自訂緩衝)

你也可以建立自訂頁面緩衝處理過程。ASP.NET提供了一種很便捷的方式來建立自訂緩衝,通過給VarByCustom屬性指定自訂的緩衝類型。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @ OutputCache Duration = " 20 " VaryByParam = " None " VaryByCustom = " browser " %>

你需要建立一個方法,該方法產生一個自訂緩衝字串。文法如下:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

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

該方法必須寫在global.asax檔案中,返回一個字串值。ASP.Net用這個值來實現緩衝。如果不同的要求方法返回相同的字串值,ASP.net重用快取頁面面除非產生了一個新的緩衝版本。在上面例子中,GetVaryByCustomString()建立了一個基於瀏覽器名稱的緩衝字串。ASP.Net將根據不同的瀏覽器請求建立不同的緩衝版本。


Control Cache(控制項緩衝)

上面的緩衝技術,能讓你很容易的緩衝整個頁面。但是如果你想緩衝指定的控制項內容,你可以通過VaryByControl屬性來緩衝一個控制項

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @ OutputCache Duration = " 20 " VaryByControl = " MyControl_1 " %>

在.aspx頁面上添加上面代碼,ASP.net將緩衝 MyControl_1控制項20秒,這樣ASP.net建立一個“MyControl_1”緩衝版本,如果緩衝沒有到期,ASP.net重用該緩衝版本,除非控制項代碼重新執行過。如果你想建立一個依賴於控制項某些屬性的控制項緩衝,ASP.net同樣很方便,只需在*.ascx控制項頁上添加OutPutCache指令。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

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

VaryByControl=”EmployeeID” 告訴ASP.net根據控制項屬性EmployeeID不同值建立不同的控制項緩衝版本。

在.ascx.cs 檔案中添加屬性”EmplyeeID“,用於ASP.net建立緩衝

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 private int _employeeID;
2 public int EmployeeID
3 {
4    get { return _employeeID; }
5    set { _employeeID = value; }
6 }
7
8 protected void Page_Load( object sender, EventArgs e)
9 {
10    lblDate.Text = DateTime.Now.ToShortDateString();
11    lblTime.Text = DateTime.Now.ToLongTimeString();
12
13    lblEmployeeID.Text = EmployeeID.ToString();
14
15 }

在頁面上添加控制項並設定”EmployeeID“

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @ Register Src = " Controls/MyControl.ascx " TagName = " MyControl " TagPrefix = " uc1 " %>
2 < asp:Content ID = " Content1 " ContentPlaceHolderID = " ContentPlaceHolder1 " runat = " Server " >
3     < div align = " center " >
4         < uc1:MyControl ID = " MyControl1 " runat = " server " EmployeeID = " 1 " ></ uc1:MyControl >
5     </ div >
6 </ asp:Content >

Cache Profile(緩衝設定檔)

ASP.net在web.config檔案中定義緩衝設定也是相當的方便。假如你在頁面中嵌入緩衝設定,並且想從20秒改為30秒,然後你必須在所有頁面中更改duration值。最好的方式就是在web.config中設定緩衝,你可以非常容易管理你的緩衝設定。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

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

現在你只需要在頁面屬性中添加CacheProfile=”ProfileName”就可以了。 <!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @ OutputCache CacheProfile = " ProductItemCacheProfile " VaryByParam = " None " %>

資料緩衝(Date Cache)

ASP.net也提供了靈活的資料緩衝。你可以把一些耗資源的項添加到對象緩衝集合中。Cache是一個索引值對集合,添加項到緩衝集合中只需要指定一個新的Key名稱。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 Cache[ " Name " ] = data;

該技術不支援緩衝對象的控制。Cache.Insert()提供了5版本的方法重載,通過使用Insert方法,你可以設定緩衝的到期策略、優先順序、依賴項等。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

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

Asp.net 允許設定絕對的或者相對的到期策略,但每次只能使用一個。


Cache dependency(緩衝依賴項)

同樣你也可以在ASP.net中設定緩衝依賴項,緩衝依賴項允許一個快取項目依賴於另一項資源,但依賴資源改變時,快取項目將自動移除。CacheDependency類用於建立依賴項。這個類有多個建構函式。你可以建立依賴於檔案或者檔案夾。如果檔案或者檔案夾改變,緩衝將到期。你也可以建立依賴於其它快取項目的依賴項。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.