gpt4 book ai didi

java - Spring WebFlux switchIfEmpty 返回不同的类型

转载 作者:行者123 更新时间:2023-12-02 19:02:52 27 4
gpt4 key购买 nike

public Mono<ServerResponse> getMessage(ServerRequest request) {
//this call returns Mono<ApiClientResponse>
return apiClient.hystrixWrappedGetMessages(request.headers().asHttpHeaders(), request.queryParams())
.switchIfEmpty(/* Here */)
}

请原谅代码略有不完整,遇到这个问题时我正在重构它。要点是它在 switchIfEmpty() 中说/* Here */的地方调用,编译器强制类型为 Mono<ApiClientResponse> ,但是当hystrixWrappedGetMessages()返回 Mono.empty()我想通过返回 204 Mono<ServerResponse> 来处理这个问题例如,否则我想返回 200。我该如何实现?

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

最佳答案

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

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());
}

关于java - Spring WebFlux switchIfEmpty 返回不同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65360312/

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