我正在尝试使用spring-data-redis的Jackson序列化特性。我正在构建一个ObjectMapper,并使用GenericJackson2JsonRedisSerializer作为redisTemplate的序列化程序:
@Configuration
public class SampleModule {
@Bean
public ObjectMapper objectMapper() {
return Jackson2ObjectMapperBuilder.json()
.serializationInclusion(JsonInclude.Include.NON_NULL) // Don’t include null values
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) //ISODate
.build();
}
@Bean
public RedisTemplate getRedisTemplate(ObjectMapper objectMapper, RedisConnectionFactory redisConnectionFactory){
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}我有一个要保存的SampleBean:
@RedisHash("sampleBean")
public class SampleBean {
@Id
String id;
String value;
Date date;
public SampleBean(String value, Date date) {
this.value = value;
this.date = date;
}
} 和该bean的存储库:
public interface SampleBeanRepository extends CrudRepository {
}然后,我尝试将bean写入Redis:
ConfigurableApplicationContext context = SpringApplication.run(SampleRedisApplication.class, args);
SampleBean helloSampleBean = new SampleBean("hello", new Date());
ObjectMapper objectMapper = context.getBean(ObjectMapper.class);
logger.info("Expecting date to be written as: " + objectMapper.writeValueAsString(helloSampleBean.date));
SampleBeanRepository repository = context.getBean(SampleBeanRepository.class);
repository.save(helloSampleBean);
context.close();我希望redisTemplate使用序列化程序将SampleBean中的日期写为时间戳,但是它被写成了一个长类型。
相关的spring-data-redis参考:http://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis:serializer完整代码示例:https://github.com/bandyguy/spring-redis-jackson-sample-broken
发布于 2017-03-03 17:03:51
模板使用的序列化程序/映射器不会影响存储库使用的序列化程序/映射器,因为存储库使用Converter实现直接在byte[]上操作,以便基于域类型元数据读取/写入数据。
有关如何编写和注册自定义Converter的指导,请参阅参考手册的Object to Hash Mapping部分。
发布于 2019-07-29 23:11:59
您是否尝试过禁用序列化功能SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
https://stackoverflow.com/questions/42542721
复制相似问题