Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

java - Redis template no clear cache

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;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...