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

Caffeine缓存YAML配置expireAfterWrite未自动清理缓存问题

Caffeine缓存30秒过期未生效的解决方法

问题原因

你在配置文件中定义了名为portalInfo的缓存及其过期规则,但@Cacheable注解未指定使用该缓存,导致Spring创建并使用了默认缓存实例,没有应用你设置的expireAfterWrite=30s过期策略。

修复步骤

  1. 修正@Cacheable注解
    在仓库类的方法上明确指定cacheNames为配置中定义的portalInfo,让缓存匹配你设置的过期规则:

    @Cacheable(cacheNames = "portalInfo", key = "'key1'", sync = true)
    List<Employee> getAllEmployee(){}
    
  2. 检查核心依赖
    确保项目已引入Spring Cache和Caffeine的必要依赖(以Maven为例):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>com.github.ben-manes.caffeine</groupId>
        <artifactId>caffeine</artifactId>
    </dependency>
    
  3. 确认缓存功能已启用
    在Spring Boot启动类上添加@EnableCaching注解,开启缓存机制:

    @SpringBootApplication
    @EnableCaching
    public class YourApplication {
        public static void main(String[] args) {
            SpringApplication.run(YourApplication.class, args);
        }
    }
    

验证方式

间隔30秒以上多次调用getAllEmployee()方法,观察是否会重新执行方法内部逻辑,以此确认缓存是否正常过期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 13:54:58