解决Redis序列化Java8的LocalDateTime问题
在从Redis获取带有LocalDateTime类型属性的对象时,产生序列化和反序列化问题解决办法
方式一:实体类上指定LocalDateTime的序列化器和反序列化器
@JsonDeserialize(using = LocalDateTimeDeserializer.class)//反序列化
@JsonSerialize(using = LocalDateTimeSerializer.class)//序列化
private LocalDateTime birthday;
【解决Redis序列化Java8的LocalDateTime问题】方式二:在Redis的配置类中指明序列化的方式
@Configuration
public class RedisConfig {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
/**
* JSON序列化
*/
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
//取消时间转换格式,默认是时间戳,同时需要设置要表现的时间格式
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false);
mapper.setDateFormat(new SimpleDateFormat("yyy-MM-dd HH:mm:ss"));
//默认序列化没有实现,反序列化有实现
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATE_TIME_FORMATTER));
//javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATE_FORMATTER));
//javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(TIME_FORMATTER));
mapper.registerModule(javaTimeModule);
//设置时区
mapper.setTimeZone(TimeZone.getDefault());
//设置格式化输出
//MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
//设置格式化输出
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
serializer.setObjectMapper(mapper);
//StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(serializer);
template.setHashKeySerializer(serializer);
template.setValueSerializer(serializer);
template.setHashValueSerializer(serializer);
return template;
}
}
Good Mai http://www.goodmai.com/
推荐阅读
- parallels|parallels desktop 解决网络初始化失败问题
- 考研英语阅读终极解决方案——阅读理解如何巧拿高分
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决
- SpringBoot调用公共模块的自定义注解失效的解决
- 解决SpringBoot引用别的模块无法注入的问题
- Spark|Spark 数据倾斜及其解决方案
- 解决SyntaxError:|解决SyntaxError: invalid syntax
- Spectrum|Spectrum 区块偶尔停止同步问题排查与解决笔记
- 一劳永逸地解决词汇量不够的问题
- Hexo代码块前后空白行问题