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

}
相关推荐
java_nnnn2 分钟前
Spring Boot 快速上手:从 Maven 到第一个 Controller
java·spring·java-ee·maven
ysu_03143 分钟前
uv实战指南-从Python版本虚拟环境到pyproject依赖管理
开发语言·python·pip·uv·虚拟环境·包管理·依赖管理
盟道科技5 分钟前
电商小程序购物车系统设计:缓存与数据库双写一致性实战
数据库·缓存·小程序
java1234_小锋6 分钟前
【技术专题】Mysql8 数据库 - Mysql8 客户端sqlyog安装以及配置
数据库·sqlyog
夕除6 分钟前
redis--集群
java·redis
蜗牛互联网7 分钟前
OLMo-core 3的token gerrymandering提醒:MoE路由要按时间窗验收
java·人工智能·wpf
奇牙coding11 分钟前
Codex C接 配置教程:的 字段从迁移时必须写完整后缀,填旧值或省略 会静默回退默认模型
java·c语言·数据库·ai
Nturmoils13 分钟前
别急着 JOIN,子查询有些场景更顺手
数据库
喜欢的名字被抢了16 分钟前
09-Redis 进阶原理篇:单线程、多线程、过期、LRU-LFU、Fork 与 Lua
数据库·redis·lua
卓怡学长20 分钟前
w193基于springboot“乐通黄骅”电动车智能充电服务小程序
java·spring boot·spring·小程序·intellij-idea