設置緩存

讓我們回到 hibernate.cfg.xml 文件中的緩存設置:

<property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.SingletEhCacheProvider"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.use_query_cache" value="true"/>

注意第一行——它包含緩存引擎類的名稱。Hibernate 實際上並沒有在內部實現緩存,而是提供了一組接口,您可以使用這些接口實現自己的緩存引擎。

流行的實現包括:

  • EHC緩存
  • 操作系統緩存
  • Swarm緩存
  • JBoss 樹緩存

EHC緩存

它可以緩存在內存或磁盤上,也可以緩存在集群緩存中,還支持可選的 Hibernate 查詢結果緩存。

操作系統緩存

通過一組豐富的過期策略和查詢緩存支持,在同一 JVM 中支持內存和磁盤緩存。

Swarm緩存

基於 JGroups 的集群緩存。它使用集群失效但不支持 Hibernate 查詢緩存。

JBoss 緩存

完全事務複製的集群緩存,也基於 JGroups 多播庫。它支持複製或失效、同步或異步通信以及樂觀和悲觀鎖定。支持 Hibernate 查詢緩存。

這些引擎不支持所有的並行訪問策略。實際情況如下表所述:

戰略/供應商 只讀 非嚴格讀寫 讀寫 事務性的
EHC緩存 X X X
操作系統緩存 X X X
Swarm緩存 X X
JBoss 緩存 X X

EHCache 配置示例

EHCache引擎有自己的配置文件,稱為 ehcache.xml。此類文件的大致內容:

<diskStore path="java.io.tmpdir"/>

<defaultCache
    maxElementsInMemory = "1000"
    eternal = "false"
    timeToIdleSeconds = "120"
    timeToLiveSeconds = "120"
    overflowToDisk = "true"
/>

<cache name = "Employee"
    maxElementsInMemory = "500"
    eternal = "true"
    timeToIdleSeconds = "0"
    timeToLiveSeconds = "0"
    overflowToDisk = "false"
/>

在這裡,您可以配置一般的緩存設置,也可以單獨為每個實體配置緩存設置。在官方文檔中閱讀更多內容。

緩存統計分析

您可能還需要檢查緩存機制的配置情況。Hibernate 專門為此提供了一個特殊的 Statistics 對象。

例子:

Statistics statistics = session.getSessionFactory().getStatistics();
CacheRegionStatistics cacheStatistics = statistics.getDomainRegionStatistics(“com.codegym.employee”);

long hitCount = cacheStatistics.getHitCount();
long missCount = cacheStatistics.getMissCount();
double hitRatio = (double) hitCount / (hitCount + missCount);

我們不會對此進行詳細介紹,因為在您用完標準緩存解決方案並需要手動改進它們之前還需要很多年。順便說一下,這個評論可能是從一個類似的案例中摘錄的:

// Dear programmer:
// When you're done "optimizing" this routine
// and realize how big of a mistake it was to do this,
// please increment the counter at the bottom as a warning
// for the next guy:
// number_of_hours_spent_here = 42