構建高性能的應用程序的非常重要一項就是使用緩存。使用緩存可以避免重新從讀取服務器端讀取數據,節省數據從客戶端到服務器間往返的時間,同時也減輕了服務器數據存取的壓力。如果客戶端非常頻繁地讀取服務器上的數據,比如生成報表,並且服務器每次獲取這些數據都經過復雜的處理邏輯,那么就可能非常有必要使用緩存。應用程序需要.NET2.0中提供了兩種不同方式的緩存:頁面輸出緩存和應用程序數據緩存。
頁面輸出緩存
我們知道asp.net服務器控件每次生成數據都要經過一個復雜的生存周期過程,參見[服務器端控件頁面生存周期]。使用頁面輸出緩存就是指內存中緩存asp.net頁面的內容,這樣每次需要這些內容都無需重新生成,取而代之的是從內存中直接讀取,這樣節省了asp.net頁面控件生成這些內容的時間,從而大大地提高了應用程序的性能。如果客戶訪問的這些頁面的內容不經常變化,這些頁面的訪問量較大,那么就非常適宜使用頁面輸出緩存。
我們可以設置兩種不同類型的頁面輸出緩存:全局頁面緩存和頁面片斷緩存。全局頁面緩存是指將整個頁面的內容都緩存在內存中供客戶端調用。而頁面片斷緩存是指在內存中緩存部分頁面的內容,而其他的部分是動態重新生成的。
頁面片斷緩存有一種較為特殊的情形是,除了頁面的某一局部內容不進行緩存,其他整個頁面是緩存起來的,這種情形叫做Post-Cache Substitution。比如,登陸后在頁面某個部分顯示用戶名處,我們就有可能用到這種情形。
使用頁面輸出緩存
可以通過兩種方式設置使用緩存。
通過web.config配置緩存如下:
<System.web>
<caching>
<outputCache enableOutputCache="true"
enableFragmentCache="true"
sendCacheControlHeader="true"
omitVaryStar="false">
</outputCache>
<caching>
</system.web>
在頁面中配置使用緩存如下:
如何從緩存中讀取數據
要從緩存中讀取數據,需要先判斷一下緩存的鍵值是否存在,因為緩存中存儲的信息是不穩定的,可能它已經被ASP.NET移去。因此推薦采用如下方式讀取緩存的內容:
string cachedString;
if (Cache["CacheItem"] != null)
{
cachedString = (string)Cache["CacheItem"];
}
else
{
Cache.Insert("CacheItem", "Hello, World."); // 設置緩存
cachedString = (string)Cache["CacheItem"]; // 讀取緩存
}
將數據添加到緩存中
string str = "a";
1。通過指定其鍵和值將項添加到緩存中
Cache["txt"] = str;
2.通過使用 Insert(重載Insert方法)方法將項添加到緩存中
Cache.Insert("txt", str);
全局頁面緩存
下面例子表示緩存時間10秒,就是說每隔10秒讀取一次系統時間。
對VaryByParam參數的一點說明:
VaryByParam 屬性功能十分強大,它允許用戶控件作者指示 ASP.NET 在服務器上緩存/存儲輸出緩存區域的多個實例。例如,前一個用戶控件的宿主頁的下列 URL 緩存用戶控件內容的單獨實例。
http://localhost/mypage.aspx?categoryid=foo&selectedid=0
http://localhost/mypage.aspx?categoryid=foo&selectedid=1
用戶控件內的邏輯因此能夠根據提供的參數動態生成不同的內容(單獨緩存)。
除了支持 VaryByParam 屬性外,片段緩存還支持 VaryByControl 屬性。VaryByParam 屬性基於使用 POST 或 GET 發送的名稱/值對改變緩存結果,而 VaryByControl 屬性則通過用戶控件中的控件改變緩存片段。例如:
<%@ OutputCache Duration="120" VaryByParam="none" VaryByControl="Category" %>
注意:與輸出緩存頁相似,即使不使用 VaryByParam,也要求顯式使用它。
例如,下列指令指示 ASP.NET 輸出緩存用戶控件 120 秒,並使用“CategoryID”和“SelectedID”查詢字符串或窗體發布參數改變緩存。
<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>
示例代碼:
<%@ Page Language="C#" %>
<%@ OutputCache Duration="10" VaryByParam="*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%Response.Write(System.DateTime.Now);%>
</div>
</form>
</body>
</html>
頁面片斷緩存
設置頁面片斷緩存可以采用<%@ Control Language="C#" ClassName="WebUserControl" %>
或者在類名前加特性[PartialCaching(3)]。
如:
<%@ Control Language="C#" ClassName="WebUserControl" %>
<%@ OutputCache Duration="10" VaryByParam="*"%>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
this.Label1.Text = System.DateTime.Now.ToString("hh:mm:ss");
this.timer.Style.Add("width", (DateTime.Now.Second * 4).ToString() + "px");
}
</script>
<div id = "timer" runat="server" style="">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
或,
[PartialCaching(3)]
public partial class WebUserControl3 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
this.Label1.Text = System.DateTime.Now.ToString("hh:mm:ss");
this.timer.Style.Add("width", (DateTime.Now.Second * 4).ToString() + "px");
}
}
應用程序數據緩存
http://files.cnblogs.com/Ring1981/Cache.rar]:
1. 建立default.aspx頁面
<%@ Page Trace="true" TraceMode="SortByCategory" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Flush Cache" OnClick="Button1_Click" />
<asp:DataGrid ID="dg1" runat="server"/>
</div>
</form>
</body>
</html>
2. 添加一個names.xml
<?xml version="1.0" encoding="utf-8" ?>
<people>
<person first="Scott" last="stafield"></person>
<person first="jim" last="Green"></person>
<person first="kate" last="Green"></person>
</people>
3.添加后台代碼
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Web.Caching;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataSet ds = null;
ds = (DataSet)Cache["names"];
if (ds == null)
{
string path = @"c:\inetpub\wwwroot\Cache\names.xml";
ds = new DataSet();
ds.ReadXml(path);
CacheDependency cd = new CacheDependency(path);
Cache.Insert("names", ds, cd);
Trace.Warn("Names read from XML file");
}
else
{
Trace.Warn("Names read from cache");
}
dg1.DataSource = ds;
dg1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Cache.Remove("names");
Response.Redirect("default.aspx");
}
}
運行程序, 第一次運行時,DataGrid里的數據是從xml文件中讀取的。 以后每次刷新,文件都是從緩存讀取的。 我們可以從每次運行時間看到,每次讀取xml文件花費時間大約0.001275s,而每次讀取緩存花費時間大約0.000044。 可見讀取緩存數據性能能夠大大地改善。
Category |
Message |
From First(s) |
From Last(s) |
Names read from XML file |
0.00155997480126664 |
0.001275 |
|
Names read from cache |
0.000343619091253218 |
0.000044 |
使用數據庫緩存:
待續...
參考文件:
MSDN 文檔
Microsoft ASP.NET 入門教: http://chs.gotdotnet.com/quickstart/aspplus/doc/quickstart.aspx
Scott stafield先生的視頻教程
添加禁查詞案例:
添加緩存:
Cache["key"] = str;
讀取緩存:
str = (StringBuilder)Cache["key"];
清除緩存:
Cache.Remove("key");