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

}
相关推荐
RFCEO1 分钟前
用手机写 Python程序解决方案
开发语言·python·智能手机·qpython环境安装
一 乐5 分钟前
健康管理|基于springboot + vue健康管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端·学习
学编程就要猛7 分钟前
MySQL:CRUD
数据库·sql·mysql
IT技术分享社区8 分钟前
MySQL实战:自动计算字段如何让查询效率翻倍?
数据库·mysql
是三好8 分钟前
分布式事务seata
java·分布式·seata
DICOM医学影像14 分钟前
15. Go-Ethereum测试Solidity ERC20合约 - Go-Ethereum调用合约方法
开发语言·后端·golang·区块链·智能合约·以太坊·web3.0
quant_198620 分钟前
如何处理大规模行情数据:从源头到终端的实战教程
大数据·开发语言·经验分享·python·金融
哆啦code梦20 分钟前
Rust:高性能安全的现代编程语言
开发语言·rust
玄同76530 分钟前
Python 装饰器:LLM API 的安全与可观测性增强
开发语言·人工智能·python·安全·自然语言处理·numpy·装饰器
为什么要做囚徒35 分钟前
多线程基础系列-线程死锁
java·多线程