You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring项目切换SimpleCacheManager为PersistentCacheManager找不到myCache报错

问题排查与解决步骤
  • 第一步:确认引入Spring对Ehcache3的适配依赖
    你当前直接返回Ehcache原生PersistentCacheManager会导致Spring缓存抽象无法识别,必须引入适配层依赖:Spring Boot 3+/Spring 6+环境引入org.springframework.boot:spring-boot-starter-cache、org.ehcache:ehcache、org.springframework.cache:spring-cache-support即可。

  • 第二步:修改CacheManager Bean配置,用Spring适配类包装原生Ehcache管理器
    Spring的缓存抽象只识别实现了org.springframework.cache.CacheManager接口的Bean,原生Ehcache管理器没有实现该接口,修改配置如下:

import org.springframework.cache.ehcache3.Ehcache3CacheManager;
// 其余import省略

@Bean
public org.springframework.cache.CacheManager cacheManager() {
    // 创建原生持久化缓存管理器
    PersistentCacheManager nativeCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
            .with(CacheManagerBuilder.persistence(new File(storagePath, "myData")))
            .withCache("myCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, NotificationListResponse.class,
                    ResourcePoolsBuilder.newResourcePoolsBuilder()
                            .disk(10, MemoryUnit.MB, true))
            )
            .build();
    nativeCacheManager.init(true);
    // 包装为Spring可识别的缓存管理器
    return new Ehcache3CacheManager(nativeCacheManager);
}
  • 第三步:验证缓存配置匹配性

    • 确认@Cacheable标注的方法返回值类型和缓存定义的NotificationListResponse完全一致,无类型不匹配或泛型擦除问题
    • 确认storagePath目录存在,且应用进程拥有该目录的读写权限,避免Ehcache持久化存储初始化失败导致缓存未注册
  • 第四步:可选:显式指定缓存管理器
    如果项目中存在多个CacheManager实例,需要在@Cacheable注解中显式指定对应的缓存管理器Bean名称:

@Cacheable(value = "myCache", cacheManager = "cacheManager", key = "'myCache' + #listType", unless = "#result.getMyList().size() == 0")
  • 第五步:检查版本兼容性
    确认Spring/Spring Boot版本和Ehcache3版本兼容,Spring Boot 3.x对应Ehcache 3.10+版本,避免版本不兼容导致适配失败。

内容的提问来源于stack exchange,提问作者Paloma Schkrab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:15:10