首页 > 数据库 >RedisTemplate序列化

RedisTemplate序列化

时间:2023-02-08 16:01:38浏览次数:48  
标签:stringRedisSerializer jackson2JsonRedisSerializer template new 序列化 RedisTemplate

1.序列化配置

public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        
        //
        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);
        
        //
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);//如果通过命令行操作,不能使用这个,只能用stringRedisSerializer
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        
        
        template.afterPropertiesSet();
        
        return template;
    }
StringRedisSerializer只能存取String类型,使用Jackson2JsonRedisSerializer
注意如果通过命令行操作,默认是stringRedisSerializer,所以使用命令行set后,不能再使用这个配置去读了。

 

标签:stringRedisSerializer,jackson2JsonRedisSerializer,template,new,序列化,RedisTemplate
From: https://www.cnblogs.com/anenyang/p/17102147.html

相关文章