【已解决】redisCache注解失效,没写cacheConfig

环境配置

复制代码
jdk11    springboot 2.6.13    

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
      <version>3.2.0</version>
</dependency>

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
      <version>3.2.0</version>
</dependency>

  redis:
    host: 192.168.2.129
    port: 6379
    username: default
    password: 'linux02'
    database: 1
#    默认使用lettuce
    lettuce:
      pool:
#        最大连接数,最大空闲数,最小空闲数
        max-active: 5
        max-idle: 2
        min-idle: 2
  #    缓存10min,允许缓存null值防止缓存穿透
  cache:
    type: redis
    redis:
      time-to-live: 600
      cache-null-values: true

代码

java 复制代码
  @Cacheable(cacheNames = BLOG_CACHE_PREFIX + "otherPassages", key = "#userId")
  @Override
  public List<PassageTitleVO> getOtherPassagesByUserId(Long userId) {
       ....
        ....
    return passageTitleVOS;
  }

解决

网上找了一些案例,有的不需要写cacheConfig,有些需要写,我之前就用过cacheable的注解,当时就是上面的配置,没写配置类也有效果,这次我最开始就没写,然后Cacheable注解就没效果了,最后写了个cacheConfig才解决。

java 复制代码
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

  @Bean
  public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    return RedisCacheManager.builder(redisConnectionFactory).build();
  }

}

然后又发现yml设置的过期时间没有生效,存到redis的是永不过期,又在 cacheConfig配置了过期时间,600s

java 复制代码
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

  @Bean
  public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofSeconds(600));
    return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(redisCacheConfiguration)
        .build();
  }

}
相关推荐
兰令水1 天前
topcode【随机算法题】【2026.5.17打卡-java版本】
java·算法·leetcode
会开花的二叉树1 天前
Qt初体验-第一个窗口程序踩的坑
开发语言·c++·qt
灰色人生qwer1 天前
python 中 BaseModel 在这里有什么用?
开发语言·python·状态模式
思麟呀1 天前
在C++基础上理解CSharp-3
开发语言·c++·c#
techdashen1 天前
Rust 能帮你捕获什么,又不能捕获什么
开发语言·后端·rust
Geometry Fu1 天前
《设计模式》2026编程作业汇总
java·c++·设计模式
YOU OU1 天前
Spring MVC 练习项目
java·后端·spring
吃好睡好便好1 天前
在Matlab中绘制柱面图
开发语言·学习·算法·matlab
Anastasiozzzz1 天前
深度解析 AI 时代的“TCP/IP协议”:Agent-to-Agent (A2A) 通信架构与多智能体协同底层逻辑
大数据·开发语言·网络·数据库·网络协议·tcp/ip·架构
wang3zc1 天前
如何设置密码复杂度策略以约束MongoDB用户的密码强度
jvm·数据库·python