gpt4 book ai didi

spring-data-redis Jackson 序列化

转载 作者:行者123 更新时间:2023-12-05 03:09:30 24 4
gpt4 key购买 nike

我正在尝试使用 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 使用 Serializer 将 SampleBean 中的 Date 写为时间戳,但它被写成 long。

相关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

最佳答案

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

请引用Object to Hash Mapping引用手册的部分,以指导如何编写和注册自定义 Converter

关于spring-data-redis Jackson 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42542721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com