Ehcache 架構核心
- 核心 Jar:
ehcache.jar
- 配置文件:
ehcache.xml(放置於 classpath 根目錄)
- 核心類:
CacheManager(管理多個 Cache)、Cache(緩存實體)、Element(鍵值對封裝)
ehcache.xml 完整配置解析
<ehcache xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<!-- 磁盤存儲路徑:內存溢出時數據持久化目錄 -->
<diskStore path="c:\\temp" />
<!-- 默認緩存策略:所有未顯式配置的緩存套用此策略 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="600"
overflowToDisk="true" />
<!-- 命名緩存:特定業務緩存的專屬策略 -->
<cache name="sampleCache"
maxElementsInMemory="5"
maxElementsOnDisk="100"
eternal="false"
timeToIdleSeconds="2"
timeToLiveSeconds="2"
overflowToDisk="true" />
</ehcache>
關鍵屬性詳細說明
| 屬性 | 含義 | 關鍵點 |
| name | 緩存唯一標識 | 通常對應領域對象類名,非強制 |
| maxElementsInMemory | 內存最大對象數 | 達到上限觸發淘汰/溢出磁盤 |
| maxElementsOnDisk | 磁盤最大對象數 | 需 overflowToDisk=true 生效 |
| eternal | 永不過期 | true 時忽略 TTL/TTI,默認 false |
| timeToIdleSeconds (TTI) | 最大空閒時間 | 超過此時間無訪問則過期,0=無限 |
| timeToLiveSeconds (TTL) | 最大生存時間 | 從創建起計時,超過則過期,0=無限。TTL > TTI 才有意義 |
| overflowToDisk | 溢出寫磁盤 | true 時內存滿寫磁盤,對象必須實現 Serializable |
Java API 核心操作
獲取 CacheManager 與 Cache
// 方式一:使用插件/工廠獲取(推薦生產環境)
CacheManager cacheManager = EhcachePlugIn.getCacheManager();
Cache cache = cacheManager.getCache("sampleCache"); // 參數對應 cache name
// 方式二:手動加載配置文件
URL url = getClass().getResource("/ehcache.xml"); // classpath 路徑
CacheManager cacheManager = new CacheManager(url);
緩存讀寫完整流程
// 1. 檢查鍵是否存在
System.out.println("Key in cache: " + cache.isKeyInCache(EHCACHE_KEY));
// 2. 獲取 Element(含值、元數據)
Element result = cache.get(EHCACHE_KEY);
if (result == null) {
System.out.println("Cache miss - loading from DB...");
List list = new ArrayList();
for (int i = 20; i < 50; i++) {
list.add(new Student(26, "kook" + i)); // Student 需實現 Serializable
}
// 3. 放入緩存
cache.put(new Element(EHCACHE_KEY, list));
cache.flush(); // 強制刷新到磁盤(如配置 overflowToDisk)
// 4. 重新獲取
result = cache.get(EHCACHE_KEY);
}
// 5. 使用數據
List ehcacheList = (List) result.getValue();
for (Student s : ehcacheList) {
System.out.println("Student: " + s.getName());
}
關鍵注意事項
- 序列化要求:
overflowToDisk="true" 時,緩存值對象必須實現 java.io.Serializable,否則磁盤寫入拋出異常。
- 線程安全:
Cache 內部線程安全,可多線程共享。
- 生命週期管理:應用關閉時調用
cacheManager.shutdown() 釋放資源、刷新磁盤。
- 集群擴展:配置文件中註釋部分展示了 RMI 多播發現的分佈式緩存配置(
cacheManagerPeerProviderFactory、cacheManagerPeerListenerFactory、RMICacheReplicatorFactory),生產環境建議使用 Terracotta 或 Ehcache 3.x 內建集群方案。
最佳實踐建議
- 業務緩存顯式命名配置,避免依賴 defaultCache 導致策略不可控。
- 根據數據熱度設置合理 TTI/TTL:熱數據長 TTL、短 TTI;冷數據相反。
- 內存緩存大小根據 JVM Heap 規劃,防止 OOM。
- 關鍵業務添加
CacheEventListener 監聽創建/更新/移除/過期事件,實現日誌、統計、異步同步 DB 等副作用。