0
votes

Trying to use a RedisTemplate bean with GenericJackson2JsonRedisSerializer, but while debugging I noticed Spring Session uses a different RedisTemplate instance.

@Configuration
@EnableRedisHttpSession
public class RedisHttpSessionConfig extends 
    AbstractHttpSessionApplicationInitializer {

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<Object, Object> redisTemplate() {
        final RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(jedisConnectionFactory());
        return template;
    }

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

When running this, Spring Session seems to use the default JdkSerializationRedisSerializer for hashValues, instead of the desired GenericJackson2JsonRedisSerializer.

Removing extends AbstractHttpSessionApplicationInitializer seems to make Spring use the correct RedisTempplate bean, but then Spring Session isn't wired at all.

Using Spring Session 1.3.3, and spring-boot-starter-data -redis 1.5.13.

Any idea what I'm missing?

2

2 Answers

2
votes

you just need to override default RedisSerializer for spring session like this

@Configuration public class RedisConfig {

@Bean(name="springSessionDefaultRedisSerializer")
public RedisSerializer serializer() {
    return new GenericJackson2JsonRedisSerializer();
}
1
votes

You need to configure and register a RedisTemplate bean named sessionRedisTemplate. This will override the default RedisTemplate instance provided by RedisHttpSessionConfiguration.

You should configure it like:

@Bean
public RedisTemplate<Object, Object> sessionRedisTemplate() {
    final RedisTemplate<Object, Object> template = new RedisTemplate<>();
    template.setKeySerializer(new StringRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());

    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setConnectionFactory(jedisConnectionFactory());
    return template;
}