2017-03-01 80 views
0

我正在尝试使用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

回答

0

使用的模板,因为库直接在所述byte[]使用操作不影响由存放库所使用的一项所述的串行器/映射器基于域类型元数据读取/写入数据的实现。

请参阅参考手册的Object to Hash Mapping部分,了解如何编写和注册自定义Converter