DEV Community

Keith
Keith

Posted on • Updated on • Originally published at Medium

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

Image description
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;
 }
}
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

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){}
Enter fullscreen mode Exit fullscreen mode

set in the applicaion.yml file

initCaches:
  fooboo: 10m
  fooboo1: 1h
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)