快取模組
AppFuse Server 提供基於分層架構 + 適配器模式的快取工具集。
核心特色
1. 介面導向設計
底層可從 Ehcache 切換到 Caffeine/Redis,應用程式碼無需修改。
2. 管理功能
- 停用/啟用: 系統維護時暫時停用快取
- 層級清除: 精確控制清除範圍
- 狀態查詢: 即時監控命中率、容量使用
3. 雙層快取架構 (DualLayerCache)
- 快速層: 短期熱資料,可過期
- 持久層: 長期全量資料,永不過期
- 自動降級: 快速層 miss 時自動查詢持久層
標準快取
基本用法
import io.leandev.appfuse.cache.*;
// 建立快取
Cache<String, User> userCache = CacheBuilder
.newCache(cacheManager, "users", String.class, User.class)
.heap(100) // 堆內 100 條
.offheap(20) // 堆外 20MB
.ttl(30) // 30 分鐘過期
.build();
// 使用快取
userCache.put("user1", user);
User user = userCache.get("user1");
userCache.remove("user1");
Cache-Aside Pattern
public Optional<User> findById(String id) {
// 1. 先查快取
User cached = userCache.get(id);
if (cached != null) {
return Optional.of(cached);
}
// 2. 快取未命中,查資料庫
return userRepository.findById(id)
.map(user -> {
// 3. 寫入快取
userCache.put(id, user);
return user;
});
}
雙層快取
適用於需要容錯的場景,如 Session 管理。
import io.leandev.appfuse.cache.*;
// 建立雙層快取
DualLayerCache<String, Session> sessionCache = DualCacheBuilder
.newCache(cacheManager, "sessions", String.class, Session.class)
.fastHeap(100) // 快速層:堆內 100 條
.fastOffheap(10) // 快速層:堆外 10MB
.fastTtl(30) // 快速層:30 分鐘過期
.store(200) // 持久層:200 條
.build();
// 自動降級:快速層 miss 時自動查詢持久層
String userId = sessionCache.get(sessionId);
// 不降級模式
String userId = sessionCache.get(sessionId, false);
雙層快取架構圖
快取模式比較
| 模式 | 適用場景 | 範例 |
|---|---|---|
| Cache-Aside | 使用者資訊、產品資料 | UserCacheService |
| Write-Through | 需要強一致性的場景 | 訂單狀態 |
| Time-to-Idle | API 限流、防爆破 | RateLimitService |
詳細 API
請參閱 Cache API 參考 或 Javadoc。