我目前正在尝试了解 Reactor 并重构了一个返回 Optional<CompanyDetails>
的服务方法,以使用 Reactor 的 Mono<CompanyDetails>
代替:
public Mono<CompanyDetails> findOne(String id) {
CompanyDetails result = retrieveFromSomewhere(id);
return Mono.justOrEmpty(result);
}
根据我的理解,这应该发出
empty()
或 just(result)
。我在 Spring Web Controller 中使用该服务,如下所示:
@RequestMapping(value = "{id}", method = RequestMethod.GET)
public DeferredResult<CompanyDetails> getCompany(@PathVariable String id) {
final DeferredResult<CompanyDetails> result = new DeferredResult<>();
companyService.findOne(id)
.consume(result::setResult);
return result;
}
如果找到结果,这可以正常工作,但是如果
findOne
发出 empty()
它会超时。我可以显式调用 get()
并检查 null
,但这感觉完全错误。另外:在重构之前,如果没有找到结果,
getCompany
会抛出一个 NotFoundException
,这完全可能吗,还是我完全走错了轨道? 最佳答案
我自己找到了答案:首先,事实证明 Reactor 的 Mono
有一个 toCompletableFuture
-method,Spring MVC 也可以使用它代替 DeferredResult
。 CompletableFuture
失败会像预期的那样抛出异常。
要失败, Mono
必须发出 error
而不是 empty
:
public Mono<CompanyDetails> findOne(String id) {
CompanyDetails result = retrieveFromSomewhere(id);
return Mono
.justOrEmpty(result)
.otherwiseIfEmpty(Mono.error(...));
}
@RequestMapping(value = "{id}", method = RequestMethod.GET)
public CompletableFuture<CompanyDetails> getCompany(@PathVariable String id) {
return companyService.findOne(id)
.toCompletableFuture();
}
现在好多了。
关于spring-mvc - 在 Spring Web Controller 中使用 Mono<T>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37180721/