我看过很多类似的问题,但我仍然找不到解决办法,所以我的问题是:
我在试着在弹靴上安装Ehcache。
Spring 2.2.6.RELEASE
Ehcache 3.8.1CacheService
我有一个名为myCache的缓存。
@Cacheable(value = "myCache")
@GetMapping("/get")
public String get();CacheConfig
还有我的配置
@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();
}
}错误
但我得到了以下错误:
java.lang.IllegalArgumentException: Cannot find cache named 'myCache' for Builder...如果我将配置放在xml文件中,我就设法让它正常工作,但我更愿意使用java。
发布于 2022-08-20 21:11:02
@Cacheable(value = "myCache")不会在Ehcache中创建名为myCache的缓存。在运行时,如果一个名为myCache的缓存在Ehcache中可用,它将使用该缓存进行缓存。如果没有,则在运行时尝试缓存时,将引发异常java.lang.IllegalArgumentException: Cannot find cache named 'myCache'。为了让@Cacheable(value = "myCache")使用Ehcache作为后端,需要在某个地方创建缓存,并且需要让Spring知道这个缓存。最简单的方法是包含spring-boot-starter-cache依赖项,将带有Ehcache配置的ehcache.xml添加到类路径中,并在application.yml中设置配置spring.cache.jcache.config: classpath:ehcache.xml。您可以在github上找到这样做的示例应用程序。
相反,如果您确实希望以编程方式配置Ehcache,则需要一个org.springframework.cache.CacheManager bean来初始化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);
}
}通过代码配置Ehcache for Spring的示例工作应用程序可以在github上找到这里。
https://stackoverflow.com/questions/72723378
复制相似问题