萬盛學電腦網

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

ASP.NET 輸出快取移除策略:頁面、使用者控制項與自訂依賴

輸出快取回顧

@ OutputCache 指令可快取整頁或使用者控制項(.ascx)輸出 HTML,大幅降低伺服器負載。但後台管理常需「立即生效」更新內容,必須手動移除快取。

案例 1:頁面層級快取移除

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

移除方式:

HttpResponse.RemoveOutputCacheItem(Page.ResolveUrl("~/Default.aspx"));
需使用 ResolveUrl 取得相對虛擬路徑(含 ~),否則找不到快取鍵值。

案例 2:使用者控制項快取移除(Shared="true")

共享快取的控制項無法直接用 RemoveOutputCacheItem 移除,需引入 VaryByCustom 機制。

步驟 1:控制項加入 VaryByCustom

<%@ OutputCache Duration="60" VaryByParam="none" Shared="true" VaryByCustom="CacheGroupClass" %>

步驟 2:Global.asax 實作 GetVaryByCustomString

public override string GetVaryByCustomString(HttpContext context, string arg)
{
    if (arg == "CacheGroupClass")
    {
        var cache = HttpRuntime.Cache;
        object flag = cache["CacheGroupClass"];
        if (flag == null)
        {
            flag = DateTime.Now.Ticks.ToString(); // 初始化版本戳記
            cache.Insert("CacheGroupClass", flag);
        }
        return flag.ToString(); // 回傳目前版本戳記
    }
    return base.GetVaryByCustomString(context, arg);
}

步驟 3:後台移除快取

var cache = HttpRuntime.Cache;
if (cache["CacheGroupClass"] != null)
    cache.Remove("CacheGroupClass"); // 移除版本戳記,強制下次請求重新產生

原理說明

VaryByCustom 回傳的字串會成為快取鍵值一部分。移除 Cache["CacheGroupClass"] 後,下一次請求 GetVaryByCustomString 會產生新的 Ticks 字串,導致快取鍵值改變,ASP.NET 視為新快取項目而重新渲染控制項。

擴充:通用快取輔助類別

public static class CacheHelper
{
    public static void Set(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration)
    {
        HttpRuntime.Cache.Insert(key, value, null, absoluteExpiration, slidingExpiration);
    }
    public static T Get<T>(string key) => HttpRuntime.Cache[key] as T;
    public static void Remove(string key) => HttpRuntime.Cache.Remove(key);
}

結語

頁面快取移除直觀簡單;控制項共享快取則需透過 VaryByCustom + HttpRuntime.Cache 版本戳記間接達成。掌握此模式,即可在保有快取效能與資料即時性之間取得平衡。

copyright © 萬盛學電腦網 all rights reserved