I am using spring data redis to set a cache value but want to have the TTL on the key defined runtime based on the incoming header value. I know I can define a bean like this :
public Entry<String, RedisCacheConfiguration> cacheConfiguration( @Qualifier("keySerializer") SerializationPair<String> keySerializer, @Qualifier("valueSerializer") SerializationPair<Object> valueSerializer, @Value("${cache.metadata.ttl:30}") long ttl, @Value("${cache.metadata.ttlTimeUnit:MINUTES}") ChronoUnit ttlTimeUnit) { String cacheName = "shoppercontext"; return Map.entry(cacheName, RedisCacheConfiguration.defaultCacheConfig() .disableCachingNullValues() .prefixKeysWith(cacheName) .serializeKeysWith(keySerializer) .serializeValuesWith(valueSerializer) .entryTtl(Duration.of(ttl, ttlTimeUnit))); }
however, this way all keys will get a static 30 mins of cache expiration. What I am looking for is to pass the TTL for each key based on a header value in the REST call and have it be done when the cache is being written, for eg. using @CachePut
. I have tried various means like trying to use RedisCacheWriter
manually or trying to "intercept" RedisCacheManager
and then trying to overwrite the TTL on the cacheConfig (unfortunately that doesn't work since entryTTL
method above returns a new config
everytime.
Any help appreciated!