ASP.NET緩存數據技巧三則
ASP.NET緩存數據技巧:訪問緩存的值
由于緩存中所存儲的信息為易失信息,即該信息可能由 ASP.NET 移除,因此建議先確定該項是否在緩存中。如果不在,則應將它重新添加到緩存中,然后檢索該項。
- string cachedString;
- if (Cache["CacheItem"] != null)
- {
- cachedString = (string)Cache["CacheItem"];
- }
- else
- {
- //緩存不存在時
- Cache.Insert("CacheItem", "Hello, World.")
- cachedString = (string)Cache["CacheItem"];
- }
ASP.NET緩存數據技巧:刪除緩存項
由于以下任一原因,緩存中的數據可能會自動移除:緩存已滿、該項已過期、依賴項發生更改。注意:如果調用 Insert 方法,并向緩存中添加與現有項同名的項,則將從緩存中刪除該舊項。顯示刪除緩存的值:
- Cache.Remove("MyCacheKey");
ASP.NET緩存數據技巧:刪除緩存項時通知應用程序
從緩存中移除項時通知應用程序,可能非常有用。例如,可能具有一個緩存的報告,創建該報告需花費大量的時間進行處理。當該報告從緩存中移除時,希望重新生成該報告,并立即將其置于緩存中,以便下次請求該報告時,用戶不必等待對此報告進行處理。
ASP.NET 提供了CacheItemRemovedCallback 委托,在從緩存中移除項時能夠發出通知。還提供 CacheItemRemovedReason 枚舉,用于指定移除緩存項的原因。舉例:假設有一個 ReportManager 對象,該對象具有兩種方法,即 GetReport 和 CacheReport。GetReport 報告方法檢查緩存以查看報告是否已緩存;如果沒有,該方法將重新生成報告并將其緩存。CacheReport 方法具有與 CacheItemRemovedCallback 委托相同的函數簽名;從緩存中移除報告時,ASP.NET 會調用 CacheReport 方法,然后將報告重新添加到緩存中。
1)創建一個 ASP.NET 網頁,該網頁將調用類中用于將項添加到緩存中的方法。
- protected void Page_Load(object sender, EventArgs e)
- {
- this.Label1.Text = ReportManager.GetReport();
- }
2)創建用于在從緩存中刪除項時處理通知的完整類ReportManager。
- using System;
- using System.Web;
- using System.Web.Caching;
- public static class ReportManager
- {
- private static bool _reportRemovedFromCache = false;
- static ReportManager() { }
- //從緩存中獲取項
- public static String GetReport()
- {
- lock (typeof(ReportManager))
- {
- if (HttpContext.Current.Cache["MyReport"] != null)
- { //存在MyReport緩存項,返回緩存值
- return (string)HttpRuntime.Cache["MyReport"];
- }
- else
- { //MyReport緩存項不存在,則創建MyReport緩存項
- CacheReport();
- return (string)HttpRuntime.Cache["MyReport"];
- }
- }
- }
- //將項以 MyReport 的名稱添加到緩存中,并將該項設置為在添加到緩存中后一分鐘過期。
- //并且該方法注冊 ReportRemoveCallback 方法,以便在從緩存中刪除項時進行調用。
- public static void CacheReport()
- {
- lock (typeof(ReportManager))
- {
- HttpContext.Current.Cache.Add("MyReport",
- CreateReport(), null, DateTime.MaxValue,
- new TimeSpan(0, 1, 0),
- System.Web.Caching.CacheItemPriority.Default,
- ReportRemovedCallback);
- }
- }
- //創建報告,該報告時MyReport緩存項的值
- private static string CreateReport()
- {
- System.Text.StringBuilder myReport =
- new System.Text.StringBuilder();
- myReport.Append("Sales Report< br />");
- myReport.Append("2005 Q2 Figures< br />");
- myReport.Append("Sales NE Region - $2 million< br />");
- myReport.Append("Sales NW Region - $4.5 million< br />");
- myReport.Append("Report Generated: " + DateTime.Now.ToString()
- + "< br />");
- myReport.Append("Report Removed From Cache: " +
- _reportRemovedFromCache.ToString());
- return myReport.ToString();
- }
- //當從緩存中刪除項時調用該方法。
- public static void ReportRemovedCallback(String key, object value,
- CacheItemRemovedReason removedReason)
- {
- _reportRemovedFromCache = true;
- CacheReport();
- }
- }
不應在 ASP.NET 頁中實現回調處理程序,因為在從緩存中刪除項之前該頁可能已被釋放,因此用于處理回調的方法將不可用,應該在非ASP.NET的程序集中實現回調處理程序。為了確保從緩存中刪除項時處理回調的方法仍然存在,請使用該方法的靜態類。但是,靜態類的缺點是需要保證所有靜態方法都是線程安全的,所以使用lock關鍵字。
本文來自菩提屋:《緩存應用程序數據(二)》
【編輯推薦】