【问题标题】:Spring WebFlux switchIfEmpty to return different typeSpring WebFlux switchIfEmpty 返回不同的类型
【发布时间】:2025-11-26 12:55:02
【问题描述】:
public Mono<ServerResponse> getMessage(ServerRequest request) {
    //this call returns Mono<ApiClientResponse>
    return apiClient.hystrixWrappedGetMessages(request.headers().asHttpHeaders(), request.queryParams())
            .switchIfEmpty(/* Here */)
}

对不起,代码有点不完整,当我遇到这个问题时,我正在对其进行重组。要点是它在 switchIfEmpty() 调用中说 /* Here */ 的地方,编译器强制类型为 Mono&lt;ApiClientResponse&gt;,但是当 hystrixWrappedGetMessages() 返回 Mono.empty() 我想通过返回 204 @987654326 来处理它@ 例如,否则我想返回 200。我怎样才能做到这一点?

理想情况下,我可以在 map 调用中检查它是否是 Mono.empty(),但如果它是空的 Mono,它似乎不会进入 map。考虑过使用可选项,但它们似乎不能很好地与 Monos 配合使用。

【问题讨论】:

    标签: java reactive-programming spring-webflux spring-webclient reactor-netty


    【解决方案1】:

    如果回复良好,您应该能够flatMap,如果返回Mono#emptyflatMap 将被忽略。

    public Mono<ServerResponse> getMessage(ServerRequest request) {
        return apiClient.hystrixWrappedGetMessages(request.headers().asHttpHeaders(), request.queryParams())
            .flatMap(response -> {
                // Do your processing here
                return ServerResponse.ok().body( .... );
            }.switchIfEmpty(ServerResponse.noContent());
    }
    

    【讨论】:

    • 啊,我想我的理解中缺少的是它是如何通过链条落下的。感谢您的回答
    最近更新 更多