没有ehcache.xml的Hibernate二级缓存

时间:2015-02-18 18:58:52

标签: java spring hibernate ehcache

我正在尝试将Ehcache配置为hibernate二级缓存,到目前为止,我发现的所有示例都指示您在类路径中创建一个ehcache.xml文件,如:

<ehcache updateCheck="false">

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

    <defaultCache maxElementsInMemory="10000" eternal="false"
        statistics="true" timeToIdleSeconds="120" timeToLiveSeconds="120"
        overflowToDisk="true" diskPersistent="false" 
        diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />

    <cache name="com.yourcompany.CachedEntity" eternal="true" maxElementsInMemory="1000" />     

</ehcache>

然后按如下方式配置Hibernate:

<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
<property name="net.sf.ehcache.configurationResourceName" value="/ehcache.xml" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.cache.use_second_level_cache" value="true" />

在我的工作场所,我们鼓励尽可能使用java配置并避免使用XML配置文件。我很感激有关如何实现这一目标的任何指示。

2 个答案:

答案 0 :(得分:1)

using ehcache in spring 4 without xml提到的stackoverflow问题learningJava显示了如何在java中配置ehcache CacheManager,但是你仍然需要一种方法来告诉hibernate它应该使用你配置的java {{1} }}

可能的方法是通过CacheManager属性配置自定义ehcache区域工厂。如果你看一下SingletonEhCacheRegionFactory的实现,你会发现在自己的hibernate.cache.region.factory_class中进行交换非常容易。

我怀疑java配置和缓存的xml配置之间的映射非常简单,但是如果ehcache在解析xml配置时在幕后执行一些“神奇的东西”,那么让你的java配置正确的工作可能有点棘手。

答案 1 :(得分:1)

我也找不到这个问题的示例代码所以我认为我会分享我的解决方案。 @Pieter的回答让我走上了正确的轨道,您需要实现自己的EhCacheRegionFactory类,以便您可以提供自定义的Java配置对象。看来库存库只支持xml。这是我的解决方案的样子:

public class CustomEhCacheRegionFactory extends EhCacheRegionFactory{

  private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
        EhCacheMessageLogger.class,
        CustomCacheRegionFactory.class.getName()
  );

  @Override
  public void start(Settings settings, Properties properties) throws CacheException {
    this.settings = settings;
    if ( manager != null ) {
        LOG.attemptToRestartAlreadyStartedEhCacheProvider();
        return;
    }

    try {

        final Configuration configuration = new Configuration();
        configuration.addCache( getEntityCacheConfiguration() );

        manager = new CacheManager( configuration );
        mbeanRegistrationHelper.registerMBean( manager, properties );
    }
    catch (net.sf.ehcache.CacheException e) {
        //handle
    }
  }

  /**
   * Create the basic second level cache configuration
   * @return
   */
  private CacheConfiguration getEntityCacheConfiguration()
  {
    CacheConfiguration config = new CacheConfiguration("entity", 50000);
    config.setTimeToIdleSeconds(86400);
    config.setTimeToLiveSeconds(86400);

    return config;
  }
}
相关问题