首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ehcache 緩存框架核心配置與 Java API 實戰指南

     編輯:Java 相關知識

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());
}

關鍵注意事項

  1. 序列化要求:overflowToDisk="true" 時,緩存值對象必須實現 java.io.Serializable,否則磁盤寫入拋出異常。
  2. 線程安全:Cache 內部線程安全,可多線程共享。
  3. 生命週期管理:應用關閉時調用 cacheManager.shutdown() 釋放資源、刷新磁盤。
  4. 集群擴展:配置文件中註釋部分展示了 RMI 多播發現的分佈式緩存配置(cacheManagerPeerProviderFactory、cacheManagerPeerListenerFactory、RMICacheReplicatorFactory),生產環境建議使用 Terracotta 或 Ehcache 3.x 內建集群方案。

最佳實踐建議

  • 業務緩存顯式命名配置,避免依賴 defaultCache 導致策略不可控。
  • 根據數據熱度設置合理 TTI/TTL:熱數據長 TTL、短 TTI;冷數據相反。
  • 內存緩存大小根據 JVM Heap 規劃,防止 OOM。
  • 關鍵業務添加 CacheEventListener 監聽創建/更新/移除/過期事件,實現日誌、統計、異步同步 DB 等副作用。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved