【已解决】redisCache注解失效,没写cacheConfig

网上找了一些案例,有的不需要写cacheConfig,有些需要写,我之前就用过cacheable的注解,当时就是上面的配置,没写配置类也有效果,这次我最开始就没写,然后Cacheable注解就没效果了,最后写了个cacheConfig才解决。

环境配置

jdk11、SpringBoot 2.6.13

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    <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>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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

代码

1
2
3
4
5
6
7
  @Cacheable(cacheNames = BLOG_CACHE_PREFIX + "otherPassages", key = "#userId")
  @Override
  public List<PassageTitleVO> getOtherPassagesByUserId(Long userId) {
       ....
        ....
    return passageTitleVOS;
  }

解决

网上找了一些案例,有的不需要写 cacheConfig,有些需要写,我之前就用过 cacheable 的注解,当时就是上面的配置,没写配置类也有效果,这次我最开始就没写,然后 Cacheable 注解就没效果了,最后写了个 cacheConfig 才解决。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

  @Bean
  public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    return RedisCacheManager.builder(redisConnectionFactory).build();
  }

}

然后又发现 yml 设置的过期时间没有生效,存到 redis 的是永不过期,又在 cacheConfig 配置了过期时间,600s

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
@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();
  }

}

comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计