Springboot annotation @Cacheable custom file set key to set expiration time and configure it in the configuration

Springboot annotation @Cacheable custom file set key to set expiration time and configure it in the configuration

custom cache with redis

·

2 min read

image.png The configuration of the Springboot RedisCacheManager class specifies the expiration time of the key and configures it in the configuration file

purpose and effect

RedisCache is configured in springBoot. When the @Cacheable annotation is used, the default is redisCache. By setting the expiration time of different keys in the configuration file, the effect of customizing the key expiration time can be achieved.

plan step1 Create a new Map class to store the key to be set

@ConfigurationProperties
public class Properties {

 private final Map<String, Duration> initCaches = Maps.newHashMap();

 public Map<String, Duration> getInitCaches() {
 return initCaches;
 }
}

step 2

Write the cacheManager in the redis configuration class and put the map set into it

@Autowired
private Properties properties;

@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
    RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMinutes(10)).disableCachingNullValues();

    RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);

    ImmutableSet.Builder<String> cacheNames = ImmutableSet.builder();
    ImmutableMap.Builder<String, RedisCacheConfiguration> cacheConfig = ImmutableMap.builder();
    for (Map.Entry<String, Duration> entry : properties.getInitCaches().entrySet()) {
        cacheNames.add(entry.getKey());
        cacheConfig.put(entry.getKey(), defaultCacheConfig.entryTtl(entry.getValue()));
    }

    return RedisCacheManager.builder(redisCacheWriter)
            .cacheDefaults(defaultCacheConfig)
            .initialCacheNames(cacheNames.build())
            .withInitialCacheConfigurations(cacheConfig.build())
            .build();
}

step3

By configuring the expiration time of the relevant key in the Springboot yml file, you can specify the expiration time of the value of @Cacheable


//Fake code@Cacheable(cacheNames = "fooboo", key = "#xxx", unless = "#result == null")
public void fooboo(String xxx){}

set in the applicaion.yml file

initCaches:
  fooboo: 10m
  fooboo1: 1h

Then the value of fooboo in the redis cache expires in 10 minutes, and the value of fooboo1 expires in 1 hour

Did you find this article valuable?

Support Kai Song by becoming a sponsor. Any amount is appreciated!