spring-data-redis Jackson 序列化

2023-12-30

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


模板使用的序列化器/映射器不会影响存储库使用的序列化器/映射器,因为存储库直接对模板进行操作byte[] using Converter基于域类型元数据读/写数据的实现。

请参阅对象到哈希映射 http://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis.repositories.mapping参考手册的部分指导如何编写和注册自定义Converter.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

spring-data-redis Jackson 序列化 的相关文章

随机推荐