【已解决】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 分钟前
从 JVM 内存模型到 GC 调优:Java 服务性能优化实战
java
CoLiuRs2 分钟前
订单不是一张表:订单聚合与状态机
数据库·架构
用户6222884048194 分钟前
Redis 内存管理与过期淘汰策略:从 maxmemory 到 LRU / LFU,一篇讲透
java·redis
shuoshuohaohao5 分钟前
Spring-boot-3 -注解 yaml配置 -日志
java·数据库·mysql
青春逝如流水8 分钟前
Java 线程池的创建方式、注意要点与任务类型判断
java·开发语言·线程池·多线程·ai文章
徐小黑ACG9 分钟前
Golang goroutine、通道、锁
开发语言·后端·golang
用户3610588626129 分钟前
深入理解Scala模式匹配:结构化解构
java
开开心心_Every10 分钟前
内存清理工具定时自动清理开机自启动
java·开发语言·spring·计算机外设·ocr·intellij-idea·excel
IT邦德17 分钟前
Bond-DBCheck 邦德智能巡检平台助力 DBA
数据库·dba
纪念 22923 分钟前
c++ string(二)
开发语言·c++