本文介紹了自定義對(duì)象映射器的問題的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在嘗試生成一些消息到Kafka主題,我想自定義Jackson對(duì)象映射器以將我的LocalDateTime
序列化為這樣的字符串2021-07-08T16:43:02Z
但這兩個(gè)都不
@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;
}
}
或者這個(gè)
spring:
jackson:
serialization:
write-dates-as-timestamps: false
起作用了,
我總是在主題中收到一條消息,字段時(shí)間為
"time": [
2021,
7,
8,
10,
46,
29,
598476000
]
應(yīng)用程序.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
...
推薦答案
這個(gè)Inject ObjectMapper into Spring Kafka serialiser/deserialiser確實(shí)有效,但我沒有使用可接受的答案
@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()));
}
}
這篇關(guān)于自定義對(duì)象映射器的問題的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,