您的位置:首页 > 数据库 > Redis

Spring-boot-redis序列化Date数据类型

2017-08-30 17:53 1566 查看
org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Can not deserialize value of type java.util.Date from String “2017-8-30 12:00:00”: not a valid representation (error: Failed to parse Date value ‘2017-8-30 12:00:00’: Unparseable date: “2017-8-30 12:00:00”)

@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
/**
* om.setDateFormat(DateFormat.getDateTimeInstance());//格式化时间
* 直接使用这种方式格式化时间的话,在Windows和在Linux上格式化后的时间格式是不一样的,
* 因为DateFormat.getDateTimeInstance()具有默认语言环境的默认格式化风格。
* Windows:2017-8-30 12:00:00
* Linux:Aug 30, 2017 12:00:00 PM
* 这样会出现这种情况:
*      在Windows上序列化之后,在Linux上反序列化时识别不了,导致反序列化失败
*      提示如下:
*      org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Can not deserialize value of type java.util.Date from String "2017-8-30 12:00:00":
*           not a valid representation (error: Failed to parse Date value '2017-8-30 12:00:00': Unparseable date: "2017-8-30 12:00:00")
*  解决办法:
*  om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
*/
//        om.setDateFormat(DateFormat.getDateTimeInstance());//格式化时间
om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  异常