java - Spring WebFlux switchIfEmpty 返回不同的类型
问题描述
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
返回 an,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());
}
推荐阅读
- django - 如何为关系模型创建或更新价值
- mysql - 订购联合查询
- java - 有什么方法可以使用 java 代码从创建的数据透视表中读取数据?
- c# - Azure 函数添加对 Sharepoint.dll 的引用失败
- angular - 获取给定格式的数组
- bash - 如何从 shell 脚本(linux)执行 git-clone 命令
- kubernetes - 尝试创建有状态集,但无法将 pv 绑定到 pvc
- python - 使用“%”运算符将数组和字符串写入文件
- excel - 试图将写在一个范围内的每个字符串缩短为只有 4 个字符长
- html - 如何使用 Clearfix 解决浮动问题