Ehcache - 找不到生成器的缓存名称

Jen*_*nga 6 ehcache spring-boot

我已经浏览了这里提出的很多类似问题,但我仍然无法找到解决方案,所以这是我的问题:

我正在尝试在 springboot 上设置 Ehcache。

Spring 2.2.6.RELEASE
Ehcache 3.8.1
Run Code Online (Sandbox Code Playgroud)

缓存服务

我有一个名为“myCache”的缓存。
@Cacheable(value = "myCache")
@GetMapping("/get")
public String get();
Run Code Online (Sandbox Code Playgroud)

缓存配置

还有我的配置
@Configuration
@EnableCaching
public class CacheConfig {    
    public CacheConfig() {          
        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("myCache",
                CacheConfigurationBuilder.newCacheConfigurationBuilder(SimpleKey.class, String.class, ResourcePoolsBuilder.heap(10))).build();
        cacheManager.init();
    }
}
Run Code Online (Sandbox Code Playgroud)

错误

但我收到以下错误:
java.lang.IllegalArgumentException: Cannot find cache named 'myCache' for Builder...
Run Code Online (Sandbox Code Playgroud)

如果我将配置放在 xml 文件中,我设法让它工作,但我宁愿将它放在 java 中。

dev*_*ock 10

@Cacheable(value = "myCache")myCache不会创建以 Ehcache命名的缓存。myCache在运行时,如果Ehcache 中存在名为 的缓存,它将使用该缓存进行缓存。java.lang.IllegalArgumentException: Cannot find cache named 'myCache'如果没有,当尝试在运行时缓存时,将抛出异常。为了@Cacheable(value = "myCache")使用 Ehcache 作为后端,需要在某处创建缓存,并且 Spring 需要了解该缓存。最简单的方法是包含spring-boot-starter-cache依赖项,将ehcache.xmlEhcache 配置添加到类路径并spring.cache.jcache.config: classpath:ehcache.xmlapplication.yml. 您可以在github上找到执行此操作的示例应用程序

相反,如果您确实想以编程方式配置 Ehcache,则需要一个org.springframework.cache.CacheManagerbean 来初始化 Ehcache 配置并将其链接到 Spring。bean 定义可能如下所示:

import javax.cache.Caching;

import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.jsr107.Eh107Configuration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.SimpleKey;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager ehCacheManager() {
        CacheConfiguration<SimpleKey, String> cacheConfig = CacheConfigurationBuilder
                .newCacheConfigurationBuilder(SimpleKey.class, String.class, ResourcePoolsBuilder.heap(10))
                .build();

        javax.cache.CacheManager cacheManager = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider")
                .getCacheManager();

        String cacheName = "myCache";
        cacheManager.destroyCache(cacheName);
        cacheManager.createCache(cacheName, Eh107Configuration.fromEhcacheCacheConfiguration(cacheConfig));

        return new JCacheCacheManager(cacheManager);
    }
}
Run Code Online (Sandbox Code Playgroud)

通过代码为 Spring 配置 Ehcache 的示例工作应用程序可以在 github找到。