首先在redis中配置是这样,使用 genericJackson2JsonRedisSerializer 这个序列器,该序列器的特点是,序列化对象时,会将对象的class也存进去。
首先是redis的配置(结合springboot,Ps:这里是2.0版本)
@Configuration
@EnableCaching
public class RedisConfig {
public static ObjectMapper mapper = new ObjectMapper();
static {
serializeCfg(mapper);
}
private static void serializeCfg(ObjectMapper objectMapper) {
JavaTimeModule javaTimeModule = new JavaTimeModule();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
javaTimeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(dtf));
javaTimeModule.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(dtf));
objectMapper.registerModule(javaTimeModule);
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
//必须加上
objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(),
ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Bean
public CacheManager cacheManager(LettuceConnectionFactory connectionFactory){
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
.fromConnectionFactory(connectionFactory)
.transactionAware();
return builder.build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//该序列化器会存储class名
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(mapper);
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
结果:可见localdatetime的字段birthday已经序列化为配置中指定的格式
{
"@class": "com.test.entity.User",
"id": "4",
"name": "测试",
"account": "test",
"password": "123456",
"email": "test@163.com",
"tel": "12306",
"birthday": "2021-03-05 12:13:14"
}
参考:https://blog.csdn.net/sinat_38278330/article/details/82150879
网友评论