首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >spring-data-redis Jackson序列化

spring-data-redis Jackson序列化
EN

Stack Overflow用户
提问于 2017-03-02 05:47:21
回答 2查看 9.2K关注 0票数 2

我正在尝试使用spring-data-redis的Jackson序列化特性。我正在构建一个ObjectMapper,并使用GenericJackson2JsonRedisSerializer作为redisTemplate的序列化程序:

代码语言:javascript
复制
    @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:

代码语言:javascript
复制
    @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的存储库:

代码语言:javascript
复制
    public interface SampleBeanRepository extends CrudRepository {
    }

然后,我尝试将bean写入Redis:

代码语言:javascript
复制
    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

EN

回答 2

Stack Overflow用户

发布于 2017-03-03 17:03:51

模板使用的序列化程序/映射器不会影响存储库使用的序列化程序/映射器,因为存储库使用Converter实现直接在byte[]上操作,以便基于域类型元数据读取/写入数据。

有关如何编写和注册自定义Converter的指导,请参阅参考手册的Object to Hash Mapping部分。

票数 4
EN

Stack Overflow用户

发布于 2019-07-29 23:11:59

您是否尝试过禁用序列化功能SerializationFeature.WRITE_DATES_AS_TIMESTAMPS

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42542721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档