redis使用Jackson2JsonRedisSerializer序列化引起的问题
@Configurationpublic class RedisConfig {@Resourceprivate RedisProperties redisProperties;@Value("${spring.redis.hotwheel.username}")private StringredisUserName;@Beanpublic <K,V> RedisTemplate<
·
@Configuration
public class RedisConfig {
@Resource
private RedisProperties redisProperties;
@Value("${spring.redis.hotwheel.username}")
private String redisUserName;
@Bean
public <K,V> RedisTemplate<K,V> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
lettuceConnectionFactory.validateConnection();
RedisTemplate<K, V> template = new RedisTemplate();
template.setConnectionFactory(lettuceConnectionFactory);
template.setKeySerializer(new GenericToStringSerializer(Object.class));
template.setHashKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
线上问题:
org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Unrecognized field "startCityName"
jackson序列化的时候,存在不认识的字段 会报错的问题,有以下两种解决方案
1,改用阿里的fastjson
2,jackson序列化默认存在不认识字段报错,用户可以自己设置忽略
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
new GenericJackson2JsonRedisSerializer(objectMapper)
更改后代码
@Configuration
public class RedisConfig {
@Resource
private RedisProperties redisProperties;
@Value("${spring.redis.hotwheel.username}")
private String redisUserName;
@Bean
public <K,V> RedisTemplate<K,V> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
lettuceConnectionFactory.validateConnection();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
RedisTemplate<K, V> template = new RedisTemplate();
template.setConnectionFactory(lettuceConnectionFactory);
template.setKeySerializer(new GenericToStringSerializer(Object.class));
template.setHashKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
return template;
}
}
更多推荐
已为社区贡献5条内容
所有评论(0)