Spring Boot集成Ehcache 2.x失效问题求助
我来帮你排查下Spring Boot集成Ehcache 2.x失效的问题,结合你给出的依赖配置,咱们一步步梳理可能的原因和解决方案:
1. 先确认Spring Boot版本适配
要注意,Spring Boot 2.x及以上版本默认支持的是Ehcache 3.x,如果你硬要集成2.x,得做额外适配;而Spring Boot 1.x对Ehcache 2.x的支持更原生。如果你的项目是Spring Boot 2.x+,这很可能是问题的根源之一。
2. 补全并规范依赖配置
你的pom里已经加了基础依赖,但Spring Boot项目最好引入spring-boot-starter-cache来简化缓存自动配置,同时指定明确的Ehcache 2.x版本,避免依赖冲突:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.6</version> <!-- 明确指定2.x版本,防止Maven自动拉取3.x --> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency>
提示:如果你的Spring Boot是2.x+,还需要确保没有自动引入Ehcache 3.x的依赖,可以用mvn dependency:tree命令检查依赖树,有冲突的话要排除掉
3. 启用缓存注解开关
在你的Spring Boot启动类上,必须加上@EnableCaching注解,否则所有缓存相关的注解(比如@Cacheable、@CachePut)都不会生效:
@SpringBootApplication @EnableCaching public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
4. 配置Ehcache核心文件
确保src/main/resources目录下存在ehcache.xml(这是Ehcache 2.x的核心配置文件),示例配置如下:
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"> <!-- 磁盘缓存存储路径 --> <diskStore path="java.io.tmpdir/ehcache"/> <!-- 默认缓存策略 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120"/> <!-- 自定义缓存,和业务中@Cacheable的value对应 --> <cache name="userCache" maxElementsInMemory="5000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true"/> </ehcache>
同时在application.properties(或yml)中指定缓存类型和配置文件位置:
application.properties
spring.cache.type=ehcache spring.cache.ehcache.config=classpath:ehcache.xml
application.yml
spring: cache: type: ehcache ehcache: config: classpath:ehcache.xml
5. 验证缓存注解的正确使用
确保业务方法上的缓存注解配置正确,比如缓存名称要和ehcache.xml里的name对应:
@Service public class UserService { @Cacheable(value = "userCache", key = "#userId") public User getUserById(Long userId) { // 模拟DB查询,第一次调用会打印,缓存生效后不会再打印 System.out.println("执行数据库查询,userId: " + userId); return new User(userId, "testUser"); } }
测试时,连续调用两次getUserById(1L),如果第一次打印日志,第二次不打印,说明缓存生效;如果两次都打印,那就要检查前面的配置是否有遗漏。
6. 排查依赖冲突
如果以上步骤都做了还是不行,用mvn dependency:tree查看依赖树,检查是否有其他缓存框架(比如Caffeine、Guava Cache)或者Ehcache 3.x的依赖被引入,有的话需要排除冲突依赖,比如:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> <exclusions> <exclusion> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> </exclusion> </exclusions> </dependency>
按照这些步骤逐一排查,应该能解决你遇到的问题。如果还是不行,可以补充下你的启动类代码、缓存方法代码以及application配置,这样能更精准定位~
内容的提问来源于stack exchange,提问作者Laodao

