轉載http://www.cnblogs.com/leochu2008/articles/1161772.html
ASP.NET Cache是提升系統效能的重要方法,它使用了“最近使用”原則(a least-recently-used algorithm)。在資料庫訪問中經常會用到Cache儲存資料庫資料。
1.緩衝的添加:
Cache的添加方法有Add()或Insert(),兩種方法幾乎類似,只是Inser方法可以使用選擇性參數,即使用預設參數,來實現緩衝的添加:
Cache.Add(
KeyName,//緩衝名
KeyValue,//要緩衝的對象
Dependencies,//依賴項
AbsoluteExpiration,//絕對到期時間
SlidingExpiration,//相對到期時間
Priority,//優先順序
CacheItemRemovedCallback);//緩衝到期引發事件
2. 緩衝依賴項:
緩衝可以設定的時效性可以通過 檔案依賴,其他緩衝依賴,資料庫依賴和到期時間方法來設定,當檔案改變,依賴快取項目改變,資料庫改變或時間的到期時,緩衝會失效,並可以引發一定事件。
2.1 檔案依賴:
CacheDependency fileDepends = new CacheDependency(Server.MapPath("Northwind.xml"));
Cache.Insert("GridViewDataSet", dsGrid, fileDepends);
此例為通過Northiwind.xml檔案依賴出來緩衝的用法:
2.2 其他快取項目依賴:
string[] fileDependsArray = {Server.MapPath("Northwind.xml")};
string[] cacheDependsArray = {"Depend0", "Depend1", "Depend2"};
CacheDependency cacheDepends = new CacheDependency(fileDependsArray, cacheDependsArray);
Cache.Insert("GridViewDataSet", dsGrid, cacheDepends);
此例設定了Northwind.xml檔案依賴和 Depend0,depend1,Depend2快取項目
其中Depend0,depend1,Depend2為另外三個緩衝。
如果不需要檔案依賴可以設定為NULL。
2.3 到期時間設定:
AbsoluteExpiration可以設定緩衝的絕對到期時間,如:
Cache.Insert("GridViewDataSet ", dsGrid, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);
緩衝會在添加起30分鐘後到期。
NoSlidingExpiration可以設定相對到期時間,如果緩衝在NoSlidingExpiration設定的時間內沒有被訪問,緩衝到期,如果在這段時間內有訪問,則緩衝到期時間將會重設為原始值,如NoSlidingExpiration=20
在20分鐘內如果沒有被訪問,緩衝到期,如果每次19分鐘訪問緩衝,緩衝將永遠不會到期。
Cache.Insert("DataGridDataSet", dsGrid, null,Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(30));
3. 優先順序:
Priority屬性值和意義:
Priority value |
Description |
NotRemovable |
Items with this priority will not be evicted. |
High |
Items with this priority level are the least likely to be evicted. |
AboveNormal |
Items with this priority level are less likely to be evicted than items assigned Normal priority. |
Default |
This is equivalent to Normal. |
Normal |
The default value. |
BelowNormal |
Items with this priority level are more likely to be evicted than items assigned Normal priority. |
Low |
Items with this priority level are the most likely to be evicted. |
4. 緩衝失效事件處理:
using System;
using System.Data;
using System.Configuration;
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.Web.Caching; // necessary for CacheDependency
using System.Xml; // necessary for Xml stuff
public partial class _Default : System.Web.UI.Page
{
public static CacheItemRemovedCallback onRemove = null;
protected void Page_Load(object sender, EventArgs e)
{
CreateGridView( );
}
private void CreateGridView( )
{
DataSet dsGrid;
dsGrid = (DataSet)Cache["GridViewDataSet"];
onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
if (dsGrid == null)
{
dsGrid = GetDataSet( );
string[] fileDependsArray = {Server.MapPath("Northwind.xml")};
string[] cacheDependsArray = {"Depend0", "Depend1", "Depend2"};
CacheDependency cacheDepends = new CacheDependency
(fileDependsArray, cacheDependsArray);
Cache.Insert("GridViewDataSet", dsGrid, cacheDepends,
DateTime.Now.AddSeconds(10),
Cache.NoSlidingExpiration,
CacheItemPriority.Default,
onRemove);
lblMessage.Text = "Data from XML file.";
}
else
{
lblMessage.Text = "Data from cache.";
}
gv.DataSource = dsGrid.Tables[0];
gv.DataBind( );
}
private DataSet GetDataSet( )
{
DataSet dsData = new DataSet( );
XmlDataDocument doc = new XmlDataDocument( );
doc.DataSet.ReadXml(Server.MapPath("Northwind.xml"));
dsData = doc.DataSet;
return dsData;
}
public void RemovedCallback(string cacheKey,
Object cacheObject,
CacheItemRemovedReason reasonToRemove)
{
WriteFile("Cache removed for following reason: " +
reasonToRemove.ToString( ));
}
private void WriteFile(string strText)
{
System.IO.StreamWriter writer = new System.IO.StreamWriter(
@"C:"test.txt", true);
string str;
str = DateTime.Now.ToString( ) + " " + strText;
writer.WriteLine(str);
writer.Close( );
}
protected void btnClear_Click(object sender, EventArgs e)
{
Cache.Remove("GridViewDataSet");
CreateGridView( );
}
protected void btnInit_Click(object sender, EventArgs e)
{
// Initialize caches to depend on.
Cache["Depend0"] = "This is the first dependency.";
Cache["Depend1"] = "This is the 2nd dependency.";
Cache["Depend2"] = "This is the 3rd dependency.";
}
protected void btnKey0_Click(object sender, EventArgs e)
{
Cache["Depend0"] = "This is a changed first dependency.";
}
}
Table 17-5. Members of the CacheItemRemovedReason enumeration |
Reason |
Description |
DependencyChanged |
A file or item key dependency has changed. |
Expired |
The cached item has expired. |
Removed |
The cached item has been explicitly removed by the Remove method or replaced by another item with the same key. |
Underused |
The cached item was removed to free up system memory. |