我正在尝试使用 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 http://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis:serializer完整代码示例:https://github.com/bandyguy/spring-redis-jackson-sample-broken https://github.com/bandyguy/spring-redis-jackson-sample-broken