Spring Boot整合Ehcache报找不到PERSON_CACHE缓存异常求助
问题原因
你遇到的Cannot find cache named 'PERSON_CACHE'报错核心是Spring缓存抽象层未识别到你定义的Ehcache缓存实例,同时配置中存在类型不匹配的隐患,具体问题点如下:
- 核心错误:你注册的Bean是Ehcache原生的
org.ehcache.CacheManager类型,Spring缓存功能默认只识别自身抽象的org.springframework.cache.CacheManager接口实现,你定义的缓存管理器没有被Spring缓存层接管,Spring会自动初始化一个空的默认缓存管理器,里面自然不存在PERSON_CACHE实例。 - 类型不匹配问题:你构建Ehcache配置时指定的缓存键类型为
Integer.class,但业务方法入参id是Long类型,后续即使缓存识别成功也会抛出类型转换异常;同时你指定的缓存值类型为Person.class,但业务方法实际返回Optional<Person>,存储时也会出现类型错误。
修正方案
- 调整缓存配置类,使用Spring提供的
EhCacheCacheManager包装原生Ehcache管理器,同时修正键、值的类型配置,修正后的CacheConfig代码如下:
package com.abdulsamadsyed.person.Config; import com.abdulsamadsyed.person.model.Person; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.ResourcePools; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.ehcache.CacheManager; import java.time.Duration; import java.util.Optional; @Configuration @EnableCaching public class CacheConfig { public final static String PERSON_CACHE = "PERSON_CACHE"; @Bean public org.springframework.cache.CacheManager cacheManager() { ResourcePools resourcePool = ResourcePoolsBuilder.heap(100).offheap(32, MemoryUnit.MB).build(); // 修正键类型为Long,值类型匹配业务方法返回的Optional<Person> CacheConfiguration<Long, Optional<Person>> configuration = CacheConfigurationBuilder .newCacheConfigurationBuilder(Long.class, (Class<Optional<Person>>)(Class<?>)Optional.class, resourcePool) .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(10))) .build(); CacheManager ehcacheNativeManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache(PERSON_CACHE, configuration) .build(); ehcacheNativeManager.init(); // 用Spring封装的缓存管理器包装原生Ehcache实例,交给Spring缓存层接管 return new EhCacheCacheManager(ehcacheNativeManager); } }
- 确认项目依赖完整:如果是Maven/Gradle项目,确保已经引入
spring-boot-starter-cache和对应版本的Ehcache依赖,避免出现版本冲突。
验证方式
配置修改完成后重启项目,第一次调用/persons/{id}接口会触发4秒休眠执行实际业务逻辑,10秒缓存有效期内重复调用相同id的接口会直接返回缓存结果,不会执行方法内的休眠和数据库查询逻辑,也不会再抛出找不到缓存的异常。
内容的提问来源于stack exchange,提问作者Abdul Samad
相关产品推荐
相关产品推荐

