SpringBoot配置Redis序列化

SpringBoot默认使用jdkSerialize方式对存入redis中的内容进行序列化,比如你要存入的key是"hello",而存入redis之后key成了\xo\12\xxx\hello这种类型的值,这显然不能用,因此我们需要自己配置redisTemplate,以下是RedisConfig.java文件

!!!!!!!!!!!!!!!!本人使用的版本是1.5.21,注意版本啊,都是泪!!!!!!!!!!!!!!!!!

    @Configuration
@EnableCaching
public class RedisConfig {

    //配置使用jedis作为redis的客户端
    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        return new JedisConnectionFactory();
    }


    @Bean
    public RedisTemplate redisTemplate(){
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory());

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
                new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();
        return template;
    }


}

再次测试,发现要存储的key是“hello”,存入redis之后的key也是"hello"

你可能感兴趣的:(SpringBoot配置Redis序列化)