如何在 SpringMVC (5.x) 项目中启用 ehCache (3.x)



在我们的项目中,我们使用ehcache 2.x,现在我们想迁移到3.x,但不知何故我失败了。在 2.x 中,我们有 ehcache.xml 中的配置 .我读到的是,在使用 3.x 时,我也需要更改内容。

但首先,我不知道如何自行连接缓存。我有

@EnableCaching
@Configuration
public class CacheConf {
  @Bean
  public CacheManager cacheManager() {
    final CacheManagerBuilder<org.ehcache.CacheManager> ret = CacheManagerBuilder.newCacheManagerBuilder();
    ret.withCache("properties", getPropCache());
    ret.withCache("propertyTypes", getPropCache());
    return (CacheManager) ret.build(true);
  }
....

但是这个配置我得到了一个java.lang.ClassCastException: org.ehcache.core.EhcacheManager cannot be cast to org.springframework.cache.CacheManager这意味着我无法正确设置ehcache

注意:在 2.x 中,我们配置了不同类型的缓存,或多或少是由于过期期限 - 并且因为其他对象类型存储在其中。

提示让它运行,因为我没有找到 Spring 5 和 ehcache 3.x 的工作示例?最好是没有 xml 的配置!

Ehcache CacheManager不是春季CacheManager。这就是为什么你会得到ClassCastException.

Ehcache 3 符合 JSR107 (JCache( 标准。所以Spring会用它连接到它。

你可以在这里找到一个例子,在Spring Boot petclinic中找到一个更简单的例子。

如果我以你为例,你会做类似的事情

@EnableCaching
@Configuration
public class CacheConf {
    @Bean
    public CacheManager cacheManager() {
        EhcacheCachingProvider provider = (EhcacheCachingProvider) Caching.getCachingProvider();
        Map<String, CacheConfiguration<?, ?>> caches = new HashMap<>();
        caches.put("properties", getPropCache());
        caches.put("propertyTypes", getPropCache());
        DefaultConfiguration configuration = new DefaultConfiguration(caches, provider.getDefaultClassLoader());
        return new JCacheCacheManager(provider.getCacheManager(provider.getDefaultURI(), configuration));
    }
  private CacheConfiguration<?, ?> getPropCache() {
    // access to the heap() could be done directly cause this returns what is required!
    final ResourcePoolsBuilder res = ResourcePoolsBuilder.heap(1000);
    // Spring does not allow anything else than Objects...
    final CacheConfigurationBuilder<Object, Object> newCacheConfigurationBuilder = CacheConfigurationBuilder
        .newCacheConfigurationBuilder(Object.class, Object.class, res);
    return newCacheConfigurationBuilder.build();
  }
}

最新更新