設計目標
將「資料來源取得邏輯」以 Lambda 表達式注入快取元件,實現:
- 宣告式定義:一行程式碼完成快取實例建立。
- 策略模式:支援
SimpleCache (記憶體)、TimeoutCache (過期淘汰)、DatabaseCache (資料庫變更通知) 等多種儲存後端。
- 串聯快取:
CacheManager 實作 ICache,可疊加多層 (L1 記憶體 → L2 Redis → L3 DB)。
介面定義
public interface ICache {
T Get(object key);
void Set(object key, T value);
}
public interface ICacheManager : ICache {
Func
三種快取策略實作
1. SimpleCache - 簡單字典
public class SimpleCache : ICache {
readonly Dictionary
2. TimeoutCache - 定期掃描過期項目
public class TimeoutCache : ICache {
public TimeSpan Expire { get; set; } = TimeSpan.FromMinutes(5);
readonly Dictionary
3. DatabaseCache - 繫結資料庫 Context 生命週期
public class DatabaseCache : ICache {
readonly Dictionary
核心 CacheManager - 串聯入口
public class CacheManager : ICacheManager {
readonly ICache _innerCache;
public Func
實際宣告與使用
// 單層快取:記憶體 + 過期策略 + DB 來源
static readonly CacheManager CompanyCache = new CacheManager(
new TimeoutCache { Expire = TimeSpan.FromMinutes(10) },
key => DbContext.Current.Companies.FirstOrDefault(c => c.Code == (string)key)
);
// 串聯快取:L1 記憶體 (1分鐘) → L2 資料庫通知快取 → 真實 DB
static readonly CacheManager CompanyCacheMulti = new CacheManager(
new TimeoutCache { Expire = TimeSpan.FromMinutes(1) },
key => {
// L2 快取同樣是 CacheManager,形成遞迴串聯
return L2Cache.Get(key);
}
);
// 使用
var company = CompanyCache.Get("COMP001"); // 自動處理 Miss → Load → Cache
CompanyCache.Set("COMP001", updatedCompany); // 手動更新/失效
進階擴充建議
- 非同步版本:
Task GetAsync(object key) 配合 Func> 來源工廠。
- 快取失效事件:
event Action OnInvalidated 通知其他節點 (分散式場景)。
- 序列化支援:
ICache 擴充 byte[] Serialize(T) / T Deserialize(byte[]) 適配 Redis/Memcached。
- 計數器/統計:內建 Hit/Miss 計數、延遲記錄,對接監控系統。