How to configure custom Redis serialization in Spring Boot?

Asked 19 hours ago 28 views

0

By default, Spring Data Redis uses standard Java JDK serialization, which outputs unreadable binary strings into Redis keys. Replacing this default setup with GenericJackson2JsonRedisSerializer enables readable JSON representations and seamless deserialization.

Spring Boot Redis Configuration

You can override default serialization by registering a custom RedisTemplate bean inside a configuration class.

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        // Connect template to underlying Redis client factory
        template.setConnectionFactory(factory);
        
        // Set plain string serializer for key names
        template.setKeySerializer(new StringRedisSerializer());
        
        // Set JSON serializer for stored values
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        
        return template;
    }
}

0 Answers


Write Your Answer