專案中常需快取熱點資料 (設定、字典、權限、報表)。重複撰寫 `if (Cache[key] == null) { Cache[key] = Load(); }` 不僅冗余,還易發生**快取擊穿** (Cache Stampede)。本文提供一個**執行緒安全、支援委派工廠、自動重載、可測試**的通用快取輔助類,並展開進階重載版本。
using System;
using System.Reflection;
using System.Web.Caching;
public static class CacheHelper
{
/// <summary>
/// 取得快取資料,不存在時透過委派工廠建立並存入
/// </summary>
/// <typeparam name="T">快取資料型別</typeparam>
/// <param name="factory">資料工廠委派 (無參或帶參)
/// <param name="cacheKey">快取鍵值</param>
/// <param name="cacheMinutes">滑動過期分鐘數</param>
/// <param name="args">工廠方法參數</param>
/// <returns>快取資料</returns>
public static T GetCacheData<T>(Func<T> factory, string cacheKey, int cacheMinutes, params object[] args)
{
if (string.IsNullOrEmpty(cacheKey)) throw new ArgumentNullException(nameof(cacheKey));
if (factory == null) throw new ArgumentNullException(nameof(factory));
var cache = HttpRuntime.Cache;
var cached = cache.Get(cacheKey);
if (cached != null) return (T)cached;
// 雙重檢查鎖定模式 (防止快取擊穿)
var lockKey = "lock_" + cacheKey;
var lockObj = new object(); // 簡易版:每次 new,實際建議用 ConcurrentDictionary 共享鎖
lock (lockObj) {
cached = cache.Get(cacheKey);
if (cached != null) return (T)cached;
// 執行工廠方法
T result;
try {
result = factory();
} catch (Exception ex) {
// 記錄日誌,決定是否快取例外或拋出
throw new CacheLoadException($"Cache factory failed for key '{cacheKey}'", ex);
}
// 存入快取:滑動過期、優先級 NotRemovable (不因記憶體壓力移除)
cache.Add(cacheKey, result, null,
Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(cacheMinutes),
CacheItemPriority.NotRemovable,
null);
return result;
}
}
}
public class CacheLoadException : Exception {
public CacheLoadException(string message, Exception inner) : base(message, inner) {}
}
// 1. 無參工廠
var settings = CacheHelper.GetCacheData(
() => LoadSettingsFromDb(),
"AppSettings",
30); // 30 分鐘滑動過期
// 2. 帶參工廠 (利用閉包捕獲參數)
var userProfile = CacheHelper.GetCacheData(
() => UserService.GetProfile(userId),
$"UserProfile_{userId}",
10);
// 3. 非同步工廠包裝 (同步封裝非同步,注意死結風險)
var data = CacheHelper.GetCacheData(
() => AsyncService.GetDataAsync(id).GetAwaiter().GetResult(),
$"Data_{id}",
5);
public enum CacheStrategy {
Sliding, // 滑動過期 (預設)
Absolute, // 絕對過期
Never // 永不過期 (需手動移除)
}
public static class CacheHelper
{
// 強型別雙參數版 (避免 params object[] 裝箱)
public static TResult GetCacheData<T1, T2, TResult>(
Func<T1, T2, TResult> factory,
string cacheKey,
int cacheMinutes,
T1 arg1,
T2 arg2,
CacheStrategy strategy = CacheStrategy.Sliding)
{
var cache = HttpRuntime.Cache;
var cached = cache.Get(cacheKey);
if (cached != null) return (TResult)cached;
var lockKey = "lock_" + cacheKey;
lock (lockKey.Intern()) { // 字串駐留共享鎖 (簡易)
cached = cache.Get(cacheKey);
if (cached != null) return (TResult)cached;
var result = factory(arg1, arg2);
InsertCache(cache, cacheKey, result, cacheMinutes, strategy);
return result;
}
}
// 非同步版本 (核心:避免同步阻塞執行緒)
public static async Task<T> GetCacheDataAsync<T>(
Func<Task<T>> factoryAsync,
string cacheKey,
int cacheMinutes,
CacheStrategy strategy = CacheStrategy.Sliding)
{
var cache = HttpRuntime.Cache;
var cached = cache.Get(cacheKey);
if (cached != null) return (T)cached;
// 非同步雙重檢查需 AsyncLock (Stephen Toub's AsyncLock 或 Nito.AsyncEx)
using (await AsyncLock.Factory.CreateLock(cacheKey).LockAsync()) {
cached = cache.Get(cacheKey);
if (cached != null) return (T)cached;
var result = await factoryAsync().ConfigureAwait(false);
InsertCache(cache, cacheKey, result, cacheMinutes, strategy);
return result;
}
}
private static void InsertCache(Cache cache, string key, object value, int minutes, CacheStrategy strategy) {
var absExp = strategy == CacheStrategy.Absolute ? DateTime.Now.AddMinutes(minutes) : Cache.NoAbsoluteExpiration;
var slidExp = strategy == CacheStrategy.Sliding ? TimeSpan.FromMinutes(minutes) : Cache.NoSlidingExpiration;
cache.Add(key, value, null, absExp, slidExp, CacheItemPriority.NotRemovable, null);
}
}
| 決策點 | 選擇 | 理由 |
|---|---|---|
| 快取儲存 | `HttpRuntime.Cache` (System.Web.Caching) | ASP.NET 內建、進程內、高效能、支援相依性/回調/優先級。非 Web 專案改用 `MemoryCache` (System.Runtime.Caching) 或 `IMemoryCache` (Microsoft.Extensions.Caching.Memory) |
| 並發控制 | `lock` + 雙重檢查 | 簡單有效。高併發建議 `Lazy<T>` 或 `AsyncLock` 避免鎖競爭 |
| 過期策略 | 滑動過期 (Sliding) 為預設 | 熱點資料自動續命,冷資料自動淘汰。靜態設定用 Absolute |
| 優先級 | `NotRemovable` | 防止記憶體壓力下被移除導致雪崩。若資料可重算、佔記憶體大,改 `Normal` |
| 工廠模式 | `Func<T>` / `Func<T1,T2,TResult>` | 延遲執行、支援閉包捕獲參數、易於單元測試 (Mock factory) |
| 異常處理 | 包裝拋出 `CacheLoadException` | 區分「快取未命中」與「資料載入失敗」,上層可決定降級/重試/記錄 |
// Startup.cs
services.AddMemoryCache(); // 注入 IMemoryCache
// Service
public class CacheService {
private readonly IMemoryCache _cache;
public CacheService(IMemoryCache cache) { _cache = cache; }
public T GetOrCreate<T>(string key, Func<ICacheEntry, T> factory, TimeSpan? sliding = null, TimeSpan? absolute = null) {
return _cache.GetOrCreate(key, entry => {
entry.SlidingExpiration = sliding ?? TimeSpan.FromMinutes(30);
if (absolute.HasValue) entry.AbsoluteExpirationRelativeToNow = absolute;
entry.Priority = CacheItemPriority.NeverRemove;
return factory(entry);
});
}
public async Task<T> GetOrCreateAsync<T>(string key, Func<ICacheEntry, Task<T>> factory, TimeSpan? sliding = null) {
return await _cache.GetOrCreateAsync(key, async entry => {
entry.SlidingExpiration = sliding ?? TimeSpan.FromMinutes(30);
entry.Priority = CacheItemPriority.NeverRemove;
return await factory(entry);
});
}
}
單機 `HttpRuntime.Cache`/`IMemoryCache` 遇到**多實例部署、Session 共享、大資料集**時需升級:
介面隔離:定義 `ICacheProvider`,實作 `MemoryCacheProvider`、`RedisCacheProvider`,DI 切換。
通用快取封裝的核心價值在於:**統一存取模式、內建防擊穿、標準化過期策略、異常隔離、易於測試與遷移**。本文提供的 `CacheHelper` 可直接納入專案共用庫,隨專案演進逐步替換底層實作 (MemoryCache → Redis → Hybrid),上層業務代碼**零修改**。記住:快取是效能倍增器,也是一致性陷阱——永遠要有「快取失效策略」與「資料不一致容忍度」的共識。