You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Reactor,如何正确并发执行Mono<Void>方法并返回查询结果?

正确实现方式

你不需要修改method1和method2的返回类型,也不用滥用Mono.zip,可以用Mono.when来实现需求:

return repository
        .get(param)
        .flatMap(response -> 
            Mono.when(method1(response), method2(response))
                .thenReturn(response)
        );

方案说明:

  • Mono.when的适配性:它专门用于等待多个Mono完成,完全忽略它们的返回值,刚好匹配你这两个返回Mono<Void>的写入方法,不需要为了适配zip而让方法返回无关的占位值。
  • thenReturn(response)的作用:在两个写入操作都执行完成后,直接返回最初从数据库获取的response,精准满足你“将get()方法响应返回给订阅者”的需求。

如果需要等待所有操作执行完毕(哪怕其中一个出错也不中断其他操作),可以改用Mono.whenDelayError,它会等所有Mono都执行结束后再抛出错误:

return repository
        .get(param)
        .flatMap(response -> 
            Mono.whenDelayError(method1(response), method2(response))
                .thenReturn(response)
        );

内容的提问来源于stack exchange,提问作者scarfebread

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 17:42:17