萬盛學電腦網

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

ASP.NET 快取處理類 CacheHandler:跨 Session 共享資料的輕量封裝

HttpRuntime.Cache 靜態封裝:簡化伺服器端快取操作

`HttpRuntime.Cache` (或 `HttpContext.Current.Cache`) 提供應用程式層級快取,跨所有 Session 共享、支援過期策略、相依性與移除回呼。本類別提供簡潔的 `Write/Read/Remove` 介面。

CacheHandler 完整程式碼

using System;
using System.Web;
using System.Web.Caching;

public static class CacheHandler
{
    /// 寫入快取,永不過期 (需手動移除)
    public static bool Write(string cacheID, object data)
    {
        if (HttpContext.Current == null) return false;
        if (String.IsNullOrEmpty(cacheID)) return false;

        HttpRuntime.Cache.Insert(
            cacheID, data, null,
            Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
            CacheItemPriority.NotRemovable, null);
        return true;
    }

    /// 讀取快取
    public static object Read(string cacheID)
    {
        if (HttpContext.Current == null) return null;
        return HttpRuntime.Cache.Get(cacheID);
    }

    /// 移除快取
    public static void Remove(string cacheID)
    {
        if (HttpContext.Current == null) return;
        if (String.IsNullOrEmpty(cacheID)) return;
        HttpRuntime.Cache.Remove(cacheID);
    }
}

使用範例

// 寫入:以 Session 專屬 Key 避免衝突
string cacheKey = "UserMenu_" + Session.SessionID;
CacheHandler.Write(cacheKey, menuData);

// 讀取
var menu = (List)CacheHandler.Read(cacheKey);
if (menu == null) { /* 重新查詢 DB */ }

// 登出/權限變更時移除
CacheHandler.Remove(cacheKey);

進階:支援過期與相依性的擴充方法

public static bool Write(string cacheID, object data, 
    TimeSpan? slidingExpiration = null, 
    DateTime? absoluteExpiration = null,
    CacheDependency dependency = null)
{
    if (HttpContext.Current == null || String.IsNullOrEmpty(cacheID)) return false;

    HttpRuntime.Cache.Insert(cacheID, data, dependency,
        absoluteExpiration ?? Cache.NoAbsoluteExpiration,
        slidingExpiration ?? Cache.NoSlidingExpiration,
        CacheItemPriority.Normal, null);
    return true;
}

// 使用:10 分鐘滑動過期
CacheHandler.Write("HotProducts", products, slidingExpiration: TimeSpan.FromMinutes(10));

// 使用:檔案相依性 (檔案變更自動失效)
var dep = new CacheDependency(Server.MapPath("~/Config/products.xml"));
CacheHandler.Write("ProductConfig", config, dependency: dep);

Cache vs Session vs Application 對比

特性CacheSessionApplication
共享範圍全應用程式單一用戶全應用程式
過期策略豐富 (絕對/滑動/相依)逾時移除無 (手動清除)
記憶體壓力管理自動淘汰 (Priority)無無
移除回呼支援不支援不支援
執行緒安全是是需 Lock

最佳實務: 唯讀/高頻讀取資料 → Cache (設定 SlidingExpiration);用戶私有狀態 → Session;全站單一實例設定 → Application/Configuration;分散式環境 → Redis/IDistributedCache。

copyright © 萬盛學電腦網 all rights reserved