storing raw json in redis by using spring-data-redis storing raw json in redis by using spring-data-redis spring spring

storing raw json in redis by using spring-data-redis


add this in your configuration to explicitly set the jackson serializer in redis template.

public @Bean RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {    RedisTemplate<Object, Object> template = new RedisTemplate<>();    template.setConnectionFactory(connectionFactory);    template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());    template.setKeySerializer(new StringRedisSerializer());    template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());    return template;}


As of spring-data-jpa:2.0.2.RELEASE at least, configuring the default redis template does not affect how the @Cacheable annotation family accesses redis.Anyway, since I'm using a redis template for more than that, it's not something I want to do.

This, however, isolates the configuration for the cache manager and works as expected:

@Configuration@EnableCachingpublic class RedisCacheManagerConfiguration {    @Autowired    private RedisConnectionFactory redisConnectionFactory;    @Bean    public CacheManager redisCacheManager() {        RedisSerializationContext.SerializationPair<Object> jsonSerializer =          RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer());         return RedisCacheManager.RedisCacheManagerBuilder                .fromConnectionFactory(redisConnectionFactory)                .cacheDefaults(                    RedisCacheConfiguration.defaultCacheConfig()                            .entryTtl(Duration.ofDays(1))                            .serializeValuesWith(jsonSerializer)                )                .build();    }}

It makes use of the generic Json serializer for Redis (GenericJackson2JsonRedisSerializer).

You can also configure other aspects of the cache manager, such as the time-to-live of the key in redis.


I managed to make this by defining RedisConnectionFactory

@Beanpublic RedisConnectionFactory jedisPool(){    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(new JedisPoolConfig());    jedisConnectionFactory.setHostName("localhost");    return jedisConnectionFactory;}

and then using StringRedisTemplate

ValueOperations<String, String> ops = redisTemplate.opsForValue();ops.set("key", "Json_string");

I hope this might help!