从GuavaCache迁移到EhCache(春季启动)

时间:2018-07-30 17:52:15

标签: java spring caching migration ehcache

由于从Spring 5.0中删除了Guava缓存,因此我尝试更改以下方法以使用EhCache缓存而不是Guava缓存。似乎没有在线文档有关如何简单地实例化EhCacheCache对象并将其传递到SimpleCacheManager。我该如何实现?

@Configuration
@EnableCaching
public class CacheConfig {

  @Bean
  public CacheManager cacheManager() {

    GuavaCache a =
        new GuavaCache("a", CacheBuilder.newBuilder().maximumSize(10000)
            .expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());

    GuavaCache b =
        new GuavaCache("b", CacheBuilder.newBuilder().maximumSize(100)
            .expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());

    GuavaCache c =
        new GuavaCache("c", CacheBuilder.newBuilder().maximumSize(100)
            .expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());

    GuavaCache d =
        new GuavaCache("d", CacheBuilder.newBuilder().maximumSize(20)
            .expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());

    GuavaCache e =
        new GuavaCache("e", CacheBuilder.newBuilder().maximumSize(100)
            .expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());

    GuavaCache f =
        new GuavaCache("f", CacheBuilder.newBuilder().maximumSize(10)
            .expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());

    GuavaCache g =
        new GuavaCache("g", CacheBuilder.newBuilder().maximumSize(5000)
            .expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());

    SimpleCacheManager simpleCacheManager = new SimpleCacheManager();

    simpleCacheManager.setCaches(
      Arrays.asList(
        a,
        b,
        c,
        d,
        e,
        f,
        g
      )
    );

    return simpleCacheManager;
  }
}

1 个答案:

答案 0 :(得分:1)

这不是它的工作方式。假设您将使用Ehcache 3.x,它符合JSR107。因此,您将使用JCacheCacheManager。看到类路径中有jcache api时,Spring-boot会不做任何配置。

实际上,最简单的方法通常是放手,然后使用JCacheManagerCustomizer添加所需的缓存。如下所示。

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public JCacheManagerCustomizer cacheManagerCustomizer() {
        return cm -> {
            cm.createCache("a", createConfiguration(100, Duration.ofHours(24)));
        };
    }

    private javax.cache.configuration.Configuration<Object, Object> createConfiguration(long size, Duration tti) {
        return Eh107Configuration.fromEhcacheCacheConfiguration(
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
                ResourcePoolsBuilder.heap(size))
                .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(tti))
                .build());
    }
}