Spring Boot 3.1.4中Caffeine缓存失效问题排查求助
问题原因及解决方案
核心问题:Utils类未被Spring容器管理
Spring的缓存注解(如@Cacheable)依赖AOP代理实现,只有被Spring IoC容器管理的Bean对象,调用其方法时才会触发缓存逻辑。你在控制器中直接通过new Utils()创建的对象不属于Spring管理,因此缓存注解完全不生效。
具体修复步骤
1. 将Utils类注册为Spring Bean
给Utils类添加@Component注解,让Spring容器接管它的实例化:
@Component public class Utils { @Cacheable(cacheNames = "testCache") // 明确指定缓存名称,避免默认值混乱 public Integer test (Integer id) { System.out.println("Not in cache : " + id); return id + 2; } }
2. 在控制器中注入Utils Bean,禁止手动new对象
修改TestController,通过@Autowired注入Spring管理的Utils实例:
@RestController public class TestController { @Autowired CacheManager cacheManager; @Autowired private Utils utils; // 注入Spring托管的Utils Bean @GetMapping("/test") public void test() { System.out.println(utils.test(3)); System.out.println(utils.test(3)); System.out.println(utils.test(4)); // 使用和@Cacheable中指定的cacheNames一致的名称获取缓存 CaffeineCache caffeineCache = (CaffeineCache) cacheManager.getCache("testCache"); if (caffeineCache != null) { Cache<Object, Object> nativeCache = caffeineCache.getNativeCache(); for (Map.Entry<Object, Object> entry : nativeCache.asMap().entrySet()) { System.out.println("Key = " + entry.getKey()); System.out.println("Value = " + entry.getValue()); } } } }
3. 关键细节:缓存名称必须一致
之前你获取缓存时用了"JSON",但未指定cacheNames的@Cacheable会自动生成复杂的默认缓存名,导致无法正确获取缓存内容。明确指定cacheNames并保持前后一致,才能保证缓存读写匹配。
修复后预期输出
Not in cache : 3 5 5 Not in cache : 4 6 Key = 3 Value = 5 Key = 4 Value = 6
内容的提问来源于stack exchange,提问作者Amaury Montero
相关产品推荐
相关产品推荐

