萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 頁面輸出快取完整指南:OutputCache 指令與進階配置

核心概念

頁面輸出快取將完整渲染後的 HTML 存放於伺服器記憶體,後續請求直接輸出快取內容,跳過頁面生命週期(Init、Load、Render 等),大幅降低 CPU 與資料庫壓力。適合低頻更新、高頻讀取的頁面(如首頁、產品列表、新聞詳情)。

基本指令語法

<%@ OutputCache Duration="60" VaryByParam="none" %>

核心屬性詳解

屬性必要說明範例值
Duration是快取秒數60, 300, 3600
VaryByParam是依查詢字串/表單參數變化快取,* 表示全部參數"id", "category;page", "*", "none"
VaryByControl否依控件屬性值變化快取(如 DropDownList 選項)"ddlCategory", "txtSearch"
VaryByCustom否自定義快取變化邏輯(需在 Global.asax 覆寫 GetVaryByCustomString)"browser", "userRole", "theme"
VaryByHeader否依 HTTP 標頭變化快取"Accept-Language", "User-Agent"
Location否快取位置:Any/Client/Server/Downstream/None"Server" (預設)
NoStore否true:不儲存任何快取(含用戶端),用於敏感頁面"true"/"false"
CacheProfile否引用 Web.config 定義的快取設定檔"LongTerm", "ShortTerm"
SqlDependency否SQL 快取相依性(資料變更自動失效)"CommandNotification"

進階配置:Web.config 快取設定檔

<configuration>
  <system.web>
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <!-- 長期快取:靜態內容、首頁 -->
          <add name="LongTerm" duration="3600" varyByParam="none" location="Server" />
          
          <!-- 短期快取:列表頁、搜尋結果 -->
          <add name="ShortTerm" duration="300" varyByParam="page;size;keyword" location="Server" />
          
          <!-- 使用者個人化:依用戶角色/語言變化 -->
          <add name="Personalized" duration="600" varyByCustom="userRole;lang" location="Server" />
          
          <!-- 無快取:敏感頁面、即時數據 -->
          <add name="NoCache" duration="0" varyByParam="none" noStore="true" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
  </system.web>
</configuration>

頁面引用設定檔

<%@ OutputCache CacheProfile="ShortTerm" %>

實戰範例

範例 1:依查詢字串分頁快取

<%@ OutputCache Duration="300" VaryByParam="page;categoryId" %>

範例 2:依控件值快取(如下拉選單篩選)

<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="true" />
<%@ OutputCache Duration="600" VaryByControl="ddlCategory" %>

範例 3:自定義快取變化(依用戶角色)

// Global.asax
public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if (custom == "userRole")
    {
        return context.User.IsInRole("Admin") ? "Admin" : "User";
    }
    return base.GetVaryByCustomString(context, custom);
}
<%@ OutputCache Duration="600" VaryByCustom="userRole" %>

範例 4:SQL 快取相依性(資料變更即時失效)

<%@ OutputCache Duration="3600" SqlDependency="CommandNotification" %>
// 需在 Web.config 啟用 sqlCacheDependency
// 並在 Global.asax Application_Start 啟用:SqlCacheDependencyAdmin.EnableNotifications(connStr)
// 以及啟用資料表:SqlCacheDependencyAdmin.EnableTableForNotifications(connStr, "Products")

程式化控制快取

// 在 Page_Load 中動態控制
protected void Page_Load(object sender, EventArgs e)
{
    // 完全禁用快取(敏感頁面)
    Response.Cache.SetNoStore();
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    
    // 或動態設定快取參數
    Response.Cache.SetExpires(DateTime.Now.AddMinutes(10));
    Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
    Response.Cache.VaryByParams["categoryId"] = true;
}

效能監控與調優

  1. 效能計數器:監控 ASP.NET Applications\Cache Total Entries、Cache Total Hit Ratio、Cache Total Turnover Rate
  2. 快取命中率:目標 > 90%,過低表示 Duration 過短或 VaryBy 過度細分
  3. 記憶體壓力:高周轉率導致 Gen 2 GC 頻繁,調大 Duration 或減少快取項目
  4. 快取碎片:大量小物件快取產生 LOH 碎片,考慮合併或使用物件快取

常見陷阱與避坑指南

陷阱後果解決
VaryByParam="*" 濫用每個查詢參數組合產生獨立快取,記憶體爆炸明確列出必要參數
快取使用者個人化頁面用戶 A 看到用戶 B 的資料VaryByCustom="userId" 或改用資料快取
Duration 設太長資料更新不及時反映配合 SqlDependency 或主動失效
Location="Client" 用於認證頁瀏覽器快取敏感資訊NoStore="true" + Location="None"
UpdatePanel 內使用 OutputCache部分頁面快取失效/衝突避免混用,改用資料層快取

結語

OutputCache 是 ASP.NET 最簡單且效果立竿見影的效能優化手段。關鍵在於精準控制快取變化維度(VaryBy* 系列)與建立失效機制(SqlDependency/主動移除)。現代架構中,配合響應式快取策略(短快取+非同步刷新),可在用戶體驗與資料新鮮度間取得最佳平衡。

copyright © 萬盛學電腦網 all rights reserved