我尝试在基于Spring Boot 2 / Spring Framework 5的Web应用程序中使用EhCache 3.5缓存功能 .
我添加了EHCache依赖:
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.0.0</version>
</dependency>
然后在src / main / resources文件夹中创建了ehcache.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">
<cache name="orders" maxElementsInMemory="100"
eternal="false" overflowToDisk="false"
memoryStoreEvictionPolicy="LFU" copyOnRead="true"
copyOnWrite="true" />
</ehcache>
Spring 5参考指南没有提到EHCache的使用,Spring 4参考指南指出:“Ehcache 3.x完全符合JSR-107标准,不需要专门的支持 . ”
所以我创建了控制器OrderController和REST endpoints :
@Cacheable("orders")
@GetMapping(path = "/{id}")
public Order findById(@PathVariable int id) {
return orderRepository.findById(id);
}
Spring Boot配置:
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
但是,当我调用此 endpoints 时,我得到一个异常:
无法为Builder找到名为'orders'的缓存[public org.Order org.OrderController.findById(int)] caches = [orders] | key =''| keyGenerator =''| cacheManager =''| cacheResolver =''| condition =''|除非=''|同步=“假”
然后我尝试使用Spring Framework 4中的示例:
@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
cmfb.setShared(true);
return cmfb;
}
但由于异常,它无法编译:
net.sf.ehcache.CacheManager类型无法解析 . 它是从所需的.class文件间接引用的
请指教 .
5 回答
这里有各种各样的东西 . 您正在使用的Ehcache 3,它通过JCache与Spring一起使用 .
这就是你需要使用
spring.cache.jcache.config=classpath:ehcache.xml
的原因 .然后,你的Ehcache配置确实和Ehcache 2配置 .
EhCacheCacheManager
也是如此 . 对于JCache,您应该使用JCacheCacheManager
. 但事实上,你甚至不需要ehcache.xml
.以下是使其工作的步骤
第1步:设置正确的依赖项 . 请注意,您不需要指定父pom依赖关系管理提供的任何版本 . javax.cache现在是1.1版 .
第2步:在
src/main/resources
中添加ehcache.xml
文件 . 以下是一个例子 .第3步:需要
application.properties
才能找到ehcache.xml
请注意,由于在类路径中找到了JCache,因此Spring Cache会选择它作为缓存提供程序 . 所以没有必要指定
spring.cache.type=jcache
.第4步:像您一样启用缓存
嗯..改变ehcache.xml,诀窍..
我做了另外的研究 . Spring Boot(来自application.properties)未选择以下配置:
所以我创建了jcache.xml并放入了src / main / resource文件夹:
然后我将application.properties中的设置更改为
现在Spring Caching正常工作 . 然而,如何获取ehcache.xml仍然是一个问题
您需要强制它使用ehcache版本2
要使用ehcache 3:
这是应用程序:
这是application.yml
这里有一个带有计数器的服务进行测试
这是一个测试,以证明它正在使用缓存:
有关工作示例,请参阅here .
面对同样的问题 .
<cache-template name =“heap-cache”> <heap unit =“entries”> 20 </ heap> </缓存模板> </配置>
已在
application.properties
中配置了spring.cache.jcache.config=classpath:ehcache.xml
在我的应用程序类上有
@EnableCaching
.在我的服务实施上有
@CacheResult
.如果有人可以指出我错过了什么,那将会非常有用 .