在 ASP.NET 提供的眾多特性中,快取對應用程式效能的潛在影響最大。記住 Steve 的快取金律:「盡早快取;經常快取」。在資料層、商務邏輯層、UI 層全面佈局快取,利用廉價記憶體換取極大的效能增益。快取也是典型的「二八法則」:20% 的努力 (設定快取) 帶來 80% 的效能提升,是效能調優的首選利器。
| 快取類型 | 適用層級 | 優點 | 缺點 | 典型場景 |
|---|---|---|---|---|
| 頁面級輸出快取 | 表現層 | 最簡單、效能最佳、無需程式碼 | 粒度粗、無法區塊化、個人化困難 | 靜態內容頁、產品目錄、報表輸出 |
| 片段快取 (用戶控制項) | 表現層 | 可快取頁面區塊、支援個人化參數 | 需拆解用戶控制項、共享快取需設定 | 導航選單、側邊欄推薦、頁首頁尾 |
| 資料快取 API (Cache 物件) | 全層級 | 彈性最高、支援相依性/回呼/過期策略 | 需手動管理、程式碼較多 | 資料層查詢結果、商務物件、計算結果 |
<%@ OutputCache Duration="60" VaryByParam="*" %>
"none" 共用單一版本;"*" 參數組合各自快取;"categoryID;page" 指定參數。Any (預設) / Client / Downstream / Server / None / ServerAndClient。Global.asax 覆寫 GetVaryByCustomString。常用 "Browser" 依瀏覽器類型區分。<%@ OutputCache Duration="60" VaryByParam="none" VaryByCustom="Browser" %>
' Global.asax
Public Overrides Function GetVaryByCustomString(context As HttpContext, custom As String) As String
If custom.Equals("Browser", StringComparison.OrdinalIgnoreCase) Then
Return context.Request.Browser.Type ' 如 "IE11", "Chrome90"
End If
Return MyBase.GetVaryByCustomString(context, custom)
End Function
<%@ Control Language="vb" %>
<%@ OutputCache Duration="120" VaryByParam="CategoryID" Shared="true" %>
<!-- 控制項標記 -->
Shared="true":同一頁面多個實例共用同一快取副本 (依 VaryByParam 區分),預設 false。' 插入/更新 (含相依性、過期、優先權、回呼)
Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback)
' 取得
Dim obj As Object = Cache(key)
' 移除
Cache.Remove(key)
Public Function GetProducts() As List(Of Product)
Const cacheKey As String = "ProductList_All"
Dim products As List(Of Product) = CType(Cache(cacheKey), List(Of Product))
If products Is Nothing Then
' 模擬資料庫查詢
products = DataAccessLayer.FetchAllProducts()
' 建立 SqlCacheDependency (需啟用資料庫通知)
Dim dep As New SqlCacheDependency("Northwind", "Products")
' 插入快取:1 小時絕對過期、高優先權、移除回呼記錄日誌
Cache.Insert(cacheKey, products, dep,
DateTime.Now.AddHours(1),
Cache.NoSlidingExpiration,
CacheItemPriority.High,
AddressOf OnProductCacheRemoved)
End If
Return products
End Function
Private Sub OnProductCacheRemoved(key As String, value As Object, reason As CacheItemRemovedReason)
' 記錄日誌、觸發預熱等
Trace.Write("Cache", $"Product cache removed: {reason}")
End Sub
CacheItemPriority 並監控記憶體使用量。Duration="0" 或 <caching enabled="false" />。ASP.NET 三大快取機制各有甜點,實務上常組合使用:頁面輸出快取處理靜態頁面、片段快取處理可重用區塊、資料快取 API 處理跨層共用資料與複雜相依邏輯。掌握其特性與參數細節,並建立快取監控與預熱機制,即能讓系統在高併發下依然從容應對。