gpt4 book ai didi

java - Spring Boot 自动配置的 Jackson ObjectMapper 默认情况下不用于 WebFlux WebClient

转载 作者:行者123 更新时间:2023-12-01 18:17:40 38 4
gpt4 key购买 nike

在我的 Spring Boot 应用程序中,我使用响应式(Reactive) WebFlux WebClient 从 SSE(服务器发送事件)端点检索流式 JSON 数据。通过在 Spring Boot 中设置配置选项来修改默认自动配置的 Jackson ObjectMapper 行为,如 official docs 建议的 spring.jackson.deserialization.read-date-timestamps-as-nanoseconds=false对 WebFlux WebClient 没有影响。我还尝试了此 SO thread 中概述的其他建议就像为 WebFlux 配置创建自定义 bean 一样,但它们没有帮助,配置仍然没有被选择。

最佳答案

花了相当长的时间调试 Spring WebFlux/Jackson 库代码后,我终于找到了解决问题的提示,查看响应式(Reactive) 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自动注入(inject),因此不需要@Autowired注解。

如果可以在官方文档中以某种方式更明确地说明这一点,那肯定会有所帮助。希望这个答案对面临类似问题的人有用!

关于java - Spring Boot 自动配置的 Jackson ObjectMapper 默认情况下不用于 WebFlux WebClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60335898/

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