Reputation: 1118
The caching still after 24 seconds, I tried to set expire on each saves caching but I want to be generic in the configuration
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = initJackson2JsonRedisSerializer();
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
template.setKeySerializer(stringSerializer);
template.setHashKeySerializer(stringSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.setDefaultSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
template.expire(CacheType.EDITORIAL_CACHE.name(), 24, TimeUnit.SECONDS);
template.expire(CacheType.S3_CACHE.name(), 24, TimeUnit.SECONDS);
return template;
}
Upvotes: 2
Views: 1330
Reputation: 17567
According to the javadoc, expire
is Set time to live for given key.
. In addition, your @Bean public RedisTemplate<String, Object> redisTemplate(...)
will be called when Spring application starts, only once.
Thus, the code you write means, "when spring starts, expire that key. But I do not care about anything after spring starts." It is different from what you want to do - as you have mentioned "I tried to set expire on each saves caching".
If you need "set expire on each saves caching", what about changing your command when saving. Instead of using SET
in redis, you should use SETEX
(see https://redis.io/commands/setex). The counterpart in Spring is, for example, void set(K key, V value, long timeout, TimeUnit unit)
(https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/ValueOperations.html).
Upvotes: 1