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

EHCache 核心 API 全攻略:CacheManager、Cache、Element 生命周期與監控指標

     編輯:Java 相關知識

EHCache 簡介

純 Java 進程內緩存庫,Hibernate 二級緩存標準實現,特點:快速、輕量、依賴少、文檔完善。官網:ehcache.sourceforge.net

CacheManager 創建方式

// 1. 單例模式(默認加載 classpath:ehcache.xml)
CacheManager singleton = CacheManager.create();

// 2. 指定配置文件路徑
CacheManager manager = new CacheManager("src/config/ehcache.xml");

// 3. 從 URL 載入
URL url = getClass().getResource("/another.xml");
CacheManager manager = new CacheManager(url);

// 4. 從 InputStream 載入
InputStream is = new FileInputStream("src/config/ehcache.xml");
CacheManager manager = new CacheManager(is); // finally 關閉流

// 獲取所有緩存名稱
String[] names = manager.getCacheNames();

Cache 創建與屬性

程序化創建

// 使用默認屬性
singleton.addCache("testCache");
Cache test = singleton.getCache("testCache");

// 自定義屬性
Cache custom = new Cache("testCache", 5000, false, false, 5, 2);
manager.addCache(custom);

構造函數參數詳解

參數含義
name緩存名稱
maxElementsInMemory內存最大對象數
overflowToDisk超出內存是否溢寫磁盤
eternaltrue=永不過期,忽略 TTL/TTI
timeToIdleSeconds最大閒置時間(兩次訪問間隔),0=無限
timeToLiveSeconds最大生存時間(創建到過期),0=無限

Cache 基礎操作

Cache cache = manager.getCache("sampleCache1");

// 存入
cache.put(new Element("key1", "value1"));

// 取值(序列化/非序列化)
Serializable valSer = cache.get("key1").getValue();
Object valObj = cache.get("key1").getObjectValue();

// 刪除
cache.remove("key1");

// 強制刷盤(持久化緩存)
cache.flush();

// 關閉管理器
CacheManager.getInstance().shutdown();

緩存統計與監控指標

// 對象數量
int size = cache.getSize();

// 內存/磁盤佔用字節數
long memSize = cache.getMemoryStoreSize();
long diskSize = cache.getDiskStoreSize();

// 命中統計
int totalHits = cache.getHitCount();
int memHits = cache.getMemoryStoreHitCount();
int diskHits = cache.getDiskStoreHitCount();

// 未命中統計
int missNotFound = cache.getMissCountNotFound(); // 鍵不存在
int missExpired = cache.getMissCountExpired();   // 已過期被淘汰

ehcache.xml 配置範本

<ehcache>
  <diskStore path="java.io.tmpdir"/>
  <defaultCache
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="120"
    timeToLiveSeconds="120"
    overflowToDisk="true"
    diskPersistent="false"
    diskExpiryThreadIntervalSeconds="120"
    memoryStoreEvictionPolicy="LRU"
  />
  <cache name="cache1"
    maxElementsInMemory="10000"
    eternal="false"
    overflowToDisk="true"
    timeToIdleSeconds="2"
    timeToLiveSeconds="3"
    memoryStoreEvictionPolicy="LFU"
  />
</ehcache>

完整 Demo 代碼

public class Demo {
    static CacheManager manager = new CacheManager();
    public static void main(String[] args) throws InterruptedException {
        String[] names = manager.getCacheNames();
        System.out.println("緩存列表:" + Arrays.toString(names));

        Cache cache = manager.getCache("cache1");
        cache.put(new Element("key1", "value1"));

        Element el = cache.get("key1");
        System.out.println("序列化值:" + el.getValue());
        System.out.println("原始對象:" + el.getObjectValue());

        System.out.println("對象數:" + cache.getSize());
        System.out.println("內存佔用:" + cache.getMemoryStoreSize());
        System.out.println("磁盤佔用:" + cache.getDiskStoreSize());
        System.out.println("總命中:" + cache.getHitCount());
        System.out.println("內存命中:" + cache.getMemoryStoreHitCount());
        System.out.println("磁盤命中:" + cache.getDiskStoreHitCount());
        System.out.println("未命中(不存在):" + cache.getMissCountNotFound());
        System.out.println("未命中(過期):" + cache.getMissCountExpired());
    }
}

生產環境建議

  • 根據業務熱點數據設置差異化 TTL/TTI
  • 啟用 diskPersistent 實現重啟預熱
  • 監控 MissCount 比率,命中率 < 80% 需調優
  • 集群環境考慮 Terracotta 分佈式緩存或 Redis 替代
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved