自定义对象映射器的问题
我正在尝试生成一些消息到Kafka主题,我想自定义Jackson对象映射器以将我的LocalDateTime
序列化为这样的字符串2021-07-08T16:43:02Z
但这两个都不
@Configuration
public class WebConfiguration {
...
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper;
}
}
或者这个
spring:
jackson:
serialization:
write-dates-as-timestamps: false
起作用了,
我总是在主题中收到一条消息,字段时间为
"time": [
2021,
7,
8,
10,
46,
29,
598476000
]
应用程序.yaml
spring:
main:
web-application-type: none
kafka:
bootstrap-servers: ${KAFKA_SERVERS}
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
...
解决方案
这个Inject ObjectMapper into Spring Kafka serialiser/deserialiser确实有效,但我没有使用可接受的答案
@Configuration
public class KafkaCustomizerConf implements DefaultKafkaProducerFactoryCustomizer {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper;
}
@Override
public void customize(DefaultKafkaProducerFactory<?, ?> producerFactory) {
producerFactory.setValueSerializer(new JsonSerializer<>(objectMapper()));
}
}
相关文章