ASP.NET緩衝

來源:互聯網
上載者:User

一:ASP.NET中緩衝分類,共3種網頁輸出快取、頁面片段快取、頁面資料緩衝 二:網頁輸出快取     
可以使用網頁輸出快取來提高WEB網站的效能。可以快取頁面面的輸出並且把緩衝起來的拷貝發送出去以響應瀏覽器的請求,而不是每次在請求頁面時執行頁面
。    
例:你的網站包括一個從資料庫表檢索出來的顯示產品資訊的頁面。預設情況下,每次使用者訪問產品頁面時,都必須執行該頁面並且從資料庫檢索資料。但如果啟用網頁輸出快取,這個頁面就只執行一次,並且只從資料庫檢索一次資料。這就意味著減輕了WEB應用程式和資料庫伺服器的負載。    
要啟用網頁輸出快取,在頁面中包括如下頁面處理指示即可:<%@ OutputCache Duration="60"
VaryByParam="none" %>如下例:<%@ Page Language="C#" %>
<%@
OutputCache Duration="300" VaryByParam="none" %>
<%@ Import
Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient"
%><script language="C#"
runat="server">void Page_Load(Object sender , EventArgs e)

{
SqlConnection conNorthwind;
string strSelect;
SqlCommand
cmdSelect;
SqlDataReader dtrProducts;conNorthwind = new SqlConnection(
@"Server=localhost;Integrated Security=SSPI;Database=Northwind" );
strSelect
= "Select * From Products Where ProductID=1";
cmdSelect = new SqlCommand(
strSelect, conNorthwind );
conNorthwind.Open();
dgrdProducts.DataSource =
cmdSelect.ExecuteReader( CommandBehavior.SingleRow
);
dgrdProducts.DataBind();
conNorthwind.Close();string strTime =
DateTime.Now.ToString();
lblMessage.Text =
strTime;
}
</script>
<html>
<head><title>ProductPage.aspx</title></head>
<body><asp:DataGrid
ID="dgrdProducts"
CellPadding="10"
Runat="Server"
/>
<hr>
<small>Last Updated:
<asp:Label
ID="lblMessage"
Font-Bold="True"
ForeColor="Blue"
Runat="Server"
/></small></body>
</html>此例中顯示了從Northwind資料庫檢索到的特定產品資訊,這個頁面被緩衝5分鐘。註:
不能保證緩衝的項總會保留在頁面的輸出緩衝中。如果系統資源不足,
ASP.NET
架構會開始從緩衝中清理快取項目。屬性
Duration
表示緩衝的時間,以秒為單位。屬性
VaryByParam
表示對一個頁面請求中包含參數
(
查詢字串參數或表單域參數
)
時頁面該如何被緩衝。這個屬性可以接受分號作為分隔字元的參數列表,或者是如下兩個特殊值:none------
表示即使頁面被請求時帶不同的參數,也不會建立頁面不同的緩衝版本。*-----------
表示在頁面被請求時帶有不同的參數,則建立頁面不同的緩衝本。如:
http://locathost/p.aspx?pid=4

       http://localhost/p.aspx?pid=5

      <%@ OutputCache Duration="300"
VaryByParam="pid" %>這條指令根據查詢字串參數
pid

設定緩衝的位置
---
屬性
Location(
取來自
OutputCacheLocation
枚舉類型的一個值
)
:Any---
預設值。頁面可在任何地方緩衝,包括伺服器、下遊伺服器、瀏覽器。Client---
頁面的輸出只在瀏覽器緩衝。DownStream----
頁面的輸出只在下遊伺服器上緩衝。None----
不執行頁面快取作業。Server----
頁面只在伺服器端緩衝。使用
HttpCachePolicy

--
精確控制頁面的緩衝行為其中
SetExpires()
方法表示頁面到期的日期,
SetCacheability()
方法表示頁面要如何來緩衝。
SetCachability()
方法取
HttpCacheability
枚舉類型中的值:NoCache---
防止任何頁面用
Cache-Control:no-cache
頭來緩衝。Private--
表示頁面不應當被Proxy 伺服器來緩衝,但可以被瀏覽器緩衝。預設值。Public--
表示頁面可以被瀏覽器和Proxy 伺服器緩衝。Server--
表示頁面只可以在伺服器端被緩衝。三:使用頁面片段快取頁面片段快取是通過使用者服務控制項來實現的。通過為頁面的每個地區建立一個單獨的使用者控制項,就可以定義頁面的不同地區。在每個使用者控制項中,可以使用
OutputCache
指令來表示如何緩衝控制項的輸出。注意:在預設情況下,每個使用者控制項的輸出都被單獨緩衝起來,如果要跨多個使用者控制項共用同樣的輸出緩衝,以節省內在開銷,那麼可以使用
Shared
屬性<%@ OutputCache Duration="60"
VaryByParam="*" Shared="true" %>頁面片段快取的限制:由於控制項被緩衝了,就不能在頁面中編程設定使用者控制項的屬性;也不能對被緩衝的使用者控制項使用資料繫結的文法。四:使用頁面資料緩衝每個ASP.NET應用程式都有一個Cache對象,直到應用程式重新啟動之前該對象一直可用。        Cache.Insert("t1",
"goodtyl");//
新增項
       
Cache.Insert("t2", "weiwei");
        Cache.Insert("t3", "haha");
       
Cache.Remove("t3");//移除項
       
//遍曆Cache,注意System.Collections.DictionaryEntry:定義可設定或可檢索的字典鍵/值對
       
foreach(DictionaryEntry temp in Cache)
        {
           
Response.Write("key: " + temp.Key.ToString() + "value: " + temp.Value.ToString()
+ "<br>");
        }
添加快取檔案依賴
:在添加一個檔案依賴時,可以把該項與一個檔案相關聯。如果檔案發生改變,就自動從緩衝中刪除該項。如例:Cache.Insert("mi","hello",new
System.Web.Caching.CacheDependency(MapPath("a.txt")));如果a.txt被修改了,那麼,mi就自動從緩衝中刪除。添加緩衝觸發依賴
:只要資料庫表的記錄發生改變就更新緩衝中的一項。需要使用sqlserver觸發器及xp_cmdshell擴充預存程序。CREATE TRIGGER UpdateCache
ON
Products
FOR UPDATE, DELETE, INSERT
AS
DECLARE @cmd Varchar( 200
)
SELECT @cmd = 'echo ' + Cast( getDATE() As Varchar( 50 ) ) +
' >
c:/tableChange.txt'
EXEC master..xp_cmdshell @cmd, no_output代碼:<%@ Page Language="C#" %>
<%@
Import Namespace="System.Data" %>
<%@ Import
Namespace="System.Data.SqlClient" %><script language="C#"
runat="server">void Page_Load(Object sender , EventArgs e)

{
DataSet dstProducts = (DataSet)(Cache[ "productsDS" ]);
if (
dstProducts == null )
{
    dstProducts = GetProducts();
   
Cache.Insert( "Products", dstProducts, new CacheDependency(
"c://tableChange.txt" ) );
}
dgrdProducts.DataSource =
dstProducts;
dgrdProducts.DataBind();
}DataSet GetProducts() {
   SqlConnection
conNorthwind;
   string strSelect;
   SqlDataAdapter dadProducts;
  
DataSet dstProducts;conNorthwind = new SqlConnection(
@"Server=localhost;Integrated Security=SSPI;Database=Northwind" );
strSelect
= "Select TOP 20 * From Products ORDER BY ProductID";
dadProducts = new
SqlDataAdapter( strSelect, conNorthwind );
dstProducts = new
DataSet();
dadProducts.Fill( dstProducts, "ProductsDS" );
return
dstProducts;
}</script><html>
<head><title>DatabaseDependency.aspx</title>
</head>
<body><asp:DataGrid
ID="dgrdProducts"
Runat="Server"
/></body>
</html>

添加緩衝鍵依賴
:<%@ Page Language="C#" %>
<script
language="C#" runat="server">void UpdateItem1( object s, EventArgs e
)
{
Cache[ "item1" ] = txtNewValue.Text;
}void UpdateItem2( object s, EventArgs e
)
{
   string arrKeyDepends = ( "item1" );
   Cache.Insert( "item2",
txtNewValue.Text, new CacheDependency( Server.MapPath(arrKeyDepends),
System.DateTime.Now ) );
}</script><html>
<head><title>KeyDependency.aspx</title></head>
<body>
<form
Runat="Server"><asp:TextBox
ID="txtNewValue"
Runat="Server"
/>
<p>
<asp:Button
Text="Update
Item1"
OnClick="UpdateItem1"
Runat="Server"
/>
<asp:Button
Text="Update
Item2"
OnClick="UpdateItem2"
Runat="Server" /><hr>Item1 = <%=Cache[ "item1"
]%>
<br>
Item2 = <%=Cache[ "item2" ]%></form>
</body>
</html>

建立一個絕對到期策略
:Cache.Insert("Time", strTime, null,
DateTime.Now.AddMinutes( 1 ), Cache.NoSlidingExpiration );建立相對到期策略
:Cache.Insert("Time", strTime, null,
Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes( 1 ) );設定快取項目的優先順序
:Cache.Insert("my","hello",null,Cache.NoAbsoluteExpiration,Cache.NoSlidingExpiration,CacheItemPriority.High,null);建立緩衝回調方法
:在插入一個項到緩衝時,可以把一個回調方法與這個項關聯起來。無論是何種原因,只要該項從緩衝中刪除,那麼回調方法就自動執行。最明顯的回調應用是當一個項到期時自動把該項重新載入到緩衝中。範例程式碼:<%@ Page Language="C#" %>
<script
language="C#" runat="server">public static CacheItemRemovedCallback
onRemove;
//CacheItemRemovedReason
表示從緩衝中刪除項的原因
void ItemRemoved( string strItemKey,
object objItemValue, CacheItemRemovedReason objRemovedReason )
{
string
strLogEntry;strLogEntry = "Item with value " +
objItemValue.ToString() ;
strLogEntry = " removed at " +
System.DateTime.Now.ToString( "T" );
strLogEntry = " because of " +
objRemovedReason.ToString();
if ( Application[ "CacheLog" ] == null
)
{
   Application[ "CacheLog" ] = new ArrayList();
}
//Application[
"CacheLog" ].Add( "strLogEntry" );
//Beep();
}void btnAddCache_Click( object s, EventArgs e
)
{
onRemove = new CacheItemRemovedCallback( ItemRemoved );
   
Cache.Insert( "myItem", txtNewValue.Text, null, DateTime.Now.AddSeconds( 10 ),
Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove );
}void btnRemoveCache_Click( object s, EventArgs
e )
{
Cache.Remove( "myItem" );
}void Page_PreRender( object s, EventArgs e
)
{
dgrdCacheLog.DataSource = Application[ "CacheLog"
];
dgrdCacheLog.DataBind();
}
</script><html>
<head><title>CacheCallback.aspx</title></head>
<body>
<form
Runat="Server"><h2>Cache
Log</h2>
<asp:DataGrid
ID="dgrdCacheLog"
CellPadding="8"
Runat="Server"
/>
<p>
<asp:TextBox
id="txtNewValue"
Runat="Server"
/>
<p>
<asp:Button
id="btnAddCache"
Text="Add To
Cache!"
OnClick="btnAddCache_Click"
Runat="Server" /><asp:Button
id="btnRemoveCache"
Text="Remove
From Cache!"
OnClick="btnRemoveCache_Click"
Runat="Server"
/><asp:Button
Text="Refresh
Page!"
Runat="Server" /></form>
</body>
</html>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.