我正在嘗試使用spring-data-redis的Jackson序列化功能。我建立一個ObjectMapper並使用GenericJackson2JsonRedisSerializer作爲串行的redisTemplate:spring-data-redis Jackson系列化
@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內的Date作爲Timestamp寫入,但是它會寫成一個long。
相關彈簧數據redis的參考:http://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis:serializer 完整代碼示例:https://github.com/bandyguy/spring-redis-jackson-sample-broken