在我的Spring Boot应用程序中,我正在使用反应性WebFlux WebClient从SSE(服务器发送事件)端点检索流JSON数据。按照official docs的建议,通过在Spring Boot中设置spring.jackson.deserialization.read-date-timestamps-as-nanoseconds=false
之类的配置选项来修改默认的自动配置的Jackson ObjectMapper行为对WebFlux WebClient无效。我还尝试了此SO thread中概述的其他建议,例如为WebFlux配置创建自定义bean,但它们没有帮助,该配置仍未被使用。
答案 0 :(得分:0)
花了很多时间调试Spring WebFlux / Jackson库代码之后,我才得以通过响应式WebFlux WebClient docs找到了解决该问题的提示。为了使WebClient使用默认的自动配置的Jackson ObjectMapper,需要一些自定义管道。解决方案是在创建WebClient的新实例时配置用于处理服务器发送事件的默认解码器。这是示例代码:
@Component
public class MarketDataFetcher implements CommandLineRunner {
// ...
private final WebClient webClient;
public MarketDataFetcher(ObjectMapper objectMapper) {
webClient = createWebClient(objectMapper);
}
private WebClient createWebClient(ObjectMapper objectMapper) {
return WebClient.builder()
.codecs(configurer -> configurer.defaultCodecs()
.serverSentEventDecoder(new Jackson2JsonDecoder(objectMapper)))
.baseUrl(BASE_URL)
.build();
}
}
ObjectMapper
由Spring自动注入,因此不需要@Autowired
注释。
如果可以在官方文档中更明确地表明这一点,那肯定会有所帮助。希望这个答案对面临类似问题的人有用!