How to use Spring Cache Redis with a custom RestTemplate?

YLombardi :

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 ?

YLombardi :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=437520&siteId=1