【问题标题】:Mono response from a method which returns void来自返回 void 的方法的单声道响应
【发布时间】:2021-04-05 18:40:50
【问题描述】:

我有一个服务方法,它不会产生任何结果,但可以返回一个 HttpException。 例子

class Service{
public void myService() throws HttpException{
//do something
}
}

我的调用类有一个应该返回 Mono 的方法。此方法调用 myService()。

class Caller{
@Autowire
Service service;

public Mono<Response> callMyService(){

return Mono.just("abc")
           .doOnSuccess(service.myService())
           .thenReturn(new Response()); //this should return Mono<Response>

}

}

我的问题是,我怎样才能以一种好的方式编写 callMyService() ? Mono.just("abc") 似乎不是正确的实现。

【问题讨论】:

    标签: spring-boot spring-webflux project-reactor


    【解决方案1】:

    您应该为此使用Mono&lt;Void&gt;。这个单声道不会转发任何数据,它只会发出错误或完成的信号。 你可以使用then()创建它

    另外,请记住doOnSuccess() 是副作用。您不应该将其用于数据处理,可能使用map()flatMap()。对于您的情况,也许您可​​以使用Mono.fromCallable(()-&gt;service.myService()),但这可能不正确,具体取决于服务的实际用途。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多