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

}
相关推荐
Ares-Wang1 分钟前
负载均衡LB》》HAproxy
运维·数据库·负载均衡
程序员小假8 分钟前
说一说 SpringBoot 中 CommandLineRunner
java·后端
Java Fans9 分钟前
如何在Windows本机安装Python并确保与Python.NET兼容
开发语言·windows·python
AI.NET 极客圈12 分钟前
.NET 原生驾驭 AI 新基建实战系列(四):Qdrant ── 实时高效的向量搜索利器
数据库·人工智能·.net
sky_ph17 分钟前
JAVA-GC浅析(一)
java·后端
爱coding的橙子18 分钟前
每日算法刷题Day24 6.6:leetcode二分答案2道题,用时1h(下次计时20min没写出来直接看题解,节省时间)
java·算法·leetcode
岁忧23 分钟前
(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)
java·c++·算法·leetcode·职场和发展·go
天天摸鱼的java工程师33 分钟前
@Autowired 注入失效?
java·后端
sss191s36 分钟前
校招 Java 面试基础题目解析学习指南含新技术实操要点
java·python·面试
编程毕设40 分钟前
【含文档+PPT+源码】基于微信小程序的旅游论坛系统的设计与实现
java·tomcat·旅游