1. The first method: Set the global default cache validity period

Inheriting CachingConfigurerSupport overrides the cacheManager method

@EnableCaching(proxyTargetClass = true)
@Configuration
public class RedisConfiguration extends CachingConfigurerSupport {

   private final RedisConnectionFactory redisConnectionFactory;

   public RedisConfiguration(RedisConnectionFactory redisConnectionFactory) {
      this.redisConnectionFactory = redisConnectionFactory;
   }


   @Override
   @Bean
   public CacheManager cacheManager(a) {
      RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            // Set the cache validity period
            .entryTtl(Duration.ofMinutes(30));
      returnRedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); }}Copy the code

Method of use

@Cacheable(cacheNames="test",key="xxx")
public String test() {
}
Copy the code

One drawback to writing like this is that you can’t set a valid time using @cacheable

2. The second method: Initialize the cache space and configure the validity period

@EnableCaching(proxyTargetClass = true)
@Configuration
public class RedisConfiguration extends CachingConfigurerSupport {

   private final RedisConnectionFactory redisConnectionFactory;

   public RedisConfiguration(RedisConnectionFactory redisConnectionFactory) {
      this.redisConnectionFactory = redisConnectionFactory;
   }


   @Override
   @Bean
   public CacheManager cacheManager(a) {
      RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            // Set the cache validity period
            .entryTtl(Duration.ofMinutes(30));





      // Set the cache expiration time
      Map<String, RedisCacheConfiguration> cacheNameMap = new HashMap<>();
      // Set the validity period of the test cache space to 1 hour
      cacheNameMap.put("test", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)));
      // Set the validity period of the test2 cache space to 2 hours
      cacheNameMap.put("test2", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(2)));

      Set<String> cacheNames = cacheNameMap.keySet();

      return RedisCacheManager
            .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
            // Set the initial cache space
            .initialCacheNames(cacheNames)
            // Load the configuration.withInitialCacheConfigurations(cacheNameMap) .cacheDefaults(redisCacheConfiguration).build(); }}Copy the code

This has the advantage of uniformly managing the valid time of the cache space, but the disadvantage is the same as above

RedisCacheManager overrides the createRedisCache method to implement the @cacheable annotation to set a custom expiration time

Custom RedisCacheManager

/** Java * User-defined cacheNames mode RedisCacheManager User-defined cacheNames mode you can set the expiration time format. Name# 12s Indicates that the cacheNames mode expires in 12 seconds (d= day,h= hour,m= minute,s = seconds) * @author wenyuan * @date 2021/7/27 */ public class MyRedisCacheManager extends RedisCacheManager { public MyRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) { super(cacheWriter, defaultCacheConfiguration); } @Override protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) { String[] array = StringUtils.delimitedListToStringArray(name, "#"); name = array[0]; If (array.length > 1) {// parse TTL // for example, 12 defaults to 12 seconds, 12d=12 days String ttlStr = array[1]; Duration duration = convertDuration(ttlStr); cacheConfig = cacheConfig.entryTtl(duration); } return super.createRedisCache(name, cacheConfig); } private Duration convertDuration(String ttlStr) { if (NumberUtil.isLong(ttlStr)) { return Duration.ofSeconds(Long.parseLong(ttlStr)); } ttlStr = ttlStr.toUpperCase(); if (ttlStr.lastIndexOf("D") ! = -1) { return Duration.parse("P" + ttlStr); } return Duration.parse("PT" + ttlStr); }}Copy the code

Create RedisConfiguration

@EnableCaching(proxyTargetClass = true)
@Configuration
public class RedisConfiguration extends CachingConfigurerSupport {

   private final RedisConnectionFactory redisConnectionFactory;

   public RedisConfiguration(RedisConnectionFactory redisConnectionFactory) {
      this.redisConnectionFactory = redisConnectionFactory;
   }


    @Override
    @Bean
    public CacheManager cacheManager(a) {
            RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            // Set the default cache validity period
            .entryTtl(Duration.ofMinutes(30));
            return newMyRedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), RedisCacheConfiguration.defaultCacheConfig()); }}Copy the code

Format cacheNames = name + “#” + time + D/H /m/s (day/hour/minute/second)

@cacheable (cacheNames = "grade# 1D ",key = "'default'") // 1 day validity period @cacheable (cacheNames = "grade# 1H ",key = "'default'") // 1 hour validity period @cacheABLE (cacheNames = "grade#1m",key = "'default'") // 1M 1 minute validity period @cacheable (cacheNames = "grade#1s",key = "'default'") // 1s 1 second validity periodCopy the code

conclusion

SpringBoot Redis provides a more convenient way to store cached data using annotations, but annotations do not provide an expiration date attribute. So you can customize the way RedisCacheManager annotations can also set the cache time, where the second method and the third method can be used in combination.