How to create RedisCacheManager in spring-data 2.0.x

Nikita picture Nikita · Jul 19, 2018 · Viewed 13.7k times · Source

I'm migrating my application from spring boot 1.5.x to 2.0.x. I want to keep jedis but I have a problem with the instantiation of RedisCacheManager.

Now constructor signature is

RedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration)

But before it was:

RedisCacheManager(RedisOperations redisOperations)

I define this bean having only RedisTemplate in scope:

@Bean
public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
    HandleRedisCacheManager redisCacheManager = new HandleRedisCacheManager(redisTemplate);
    redisCacheManager.setUsePrefix(true);
    return redisCacheManager;
}

How is it supposed to be created now?

Answer

Starry picture Starry · Jan 10, 2019

try following code , it works for me on spring-boot 2.1.0.RELEASE

@Bean
public RedisCacheManager redisCacheManager(LettuceConnectionFactory lettuceConnectionFactory) {
    RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .disableCachingNullValues()
            .entryTtl(Duration.ofHours(1))
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));
    redisCacheConfiguration.usePrefix();

   return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(lettuceConnectionFactory)
                    .cacheDefaults(redisCacheConfiguration).build();

}