【已解决】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();
  }

}
相关推荐
todoitbo10 分钟前
MongoDB迁移之后,Spring Data 和 Hibernate 各自接哪类请求
大数据·数据库·mongodb·spring·hibernate·金仓数据库
暴力求解17 分钟前
C++ ---继承(二)
开发语言·c++·算法
猫猫.15321 分钟前
IO、存储、硬盘、文件系统详细总结
java·java-ee
陈飞EXCEL27 分钟前
北京杰飞 IT 旗下妙码生花少儿Python编程上线两大学习系统
开发语言·python·学习
HEJOO934 分钟前
数据库日期类型字段如何选型:跨数据库兼容的实践指南
数据库
SL_staff41 分钟前
设备离线时业务不中断:JVS-IOT高可用架构解析
java·物联网·产品
这个DBA有点耶1 小时前
主库秒级,从库延迟2小时:深挖Online DDL回放的MDL阻塞与算法降级机制
数据库·sql·dba
郭小李1 小时前
mybatis 动态 sql
java·sql·mybatis
代龙涛1 小时前
WordPress Query 查询机制详解(WP_Query)
开发语言·后端·php·wordpress
瑞码空间1 小时前
JSP与Servlet核心开发与CRUD实战笔记
java·笔记·servlet·jsp