Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spring Cache Redis with a custom RestTemplate?

I'm migrating my Spring application from Spring-boot 1.5.9 to Spring-boot 2.0.0. With this new Spring bundle, I have some issues with caching data in Redis.

In my Configuration, I have 3 CacheManager with differents TTL (long, medium and short) :

@Bean(name = "longLifeCacheManager")
public CacheManager longLifeCacheManager() {
    RedisCacheConfiguration cacheConfiguration =
            RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofSeconds(redisExpirationLong))
                    .disableCachingNullValues();
    return RedisCacheManager.builder(jedisConnectionFactory()).cacheDefaults(cacheConfiguration).build();
}

I also have a custom RestTemplate :

@Bean
public RedisTemplate<?, ?> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<?, ?> template = new RedisTemplate<>();
    template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
    template.setConnectionFactory(connectionFactory);
    return template;
}

With the previous Spring version, every data that is cached use this RestTemplate and was serialized with the GenericJackson2JsonRedisSerializer.

With the new Spring version, the CacheManager don't use the RestTemplate but use its own SerializationPair. This result to everything beeing serialized with the default JdkSerializationRedisSerializer.

Is it possible to configure the CacheManager to use the RestTemplate and how ? If it is not possible, what can I do to use the JacksonSerializer instead of the JdkSerializer ?

like image 947
YLombardi Avatar asked Feb 26 '18 15:02

YLombardi


1 Answers

I finally found a working solution. I can't configure the CacheManager to use my RedisTemplate, but I can set the Serializer like this :

@Bean(name = "longLifeCacheManager")
public CacheManager longLifeCacheManager(JedisConnectionFactory jedisConnectionFactory) {
    RedisCacheConfiguration cacheConfiguration =
            RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofSeconds(redisExpirationLong))
                    .disableCachingNullValues()
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
    return RedisCacheManager.builder(jedisConnectionFactory).cacheDefaults(cacheConfiguration).build();
}

The serializeValuesWith method is the key.

like image 186
YLombardi Avatar answered Oct 20 '22 05:10

YLombardi