Spring mvc 消费单声道<;T>;在SpringWeb控制器中
我目前正在尝试理解Reactor,并重构了一个服务方法,该方法返回了一个Spring mvc 消费单声道<;T>;在SpringWeb控制器中,spring-mvc,asynchronous,reactor,Spring Mvc,Asynchronous,Reactor,我目前正在尝试理解Reactor,并重构了一个服务方法,该方法返回了一个可选,以使用Reactor的Mono: public Mono<CompanyDetails> findOne(String id) { CompanyDetails result = retrieveFromSomewhere(id); return Mono.justOrEmpty(result); } 如果找到一个结果,这可以正常工作,但如果findOne发出empty()则会超时。我可以
可选
,以使用Reactor的Mono
:
public Mono<CompanyDetails> findOne(String id) {
CompanyDetails result = retrieveFromSomewhere(id);
return Mono.justOrEmpty(result);
}
如果找到一个结果,这可以正常工作,但如果findOne
发出empty()
则会超时。我可以显式调用get()
并检查null
,但这感觉完全不对
另外:在重构之前,
getCompany
抛出了一个NotFoundException
,如果找不到任何结果,这可能吗,还是我完全走错了路?自己找到了答案:首先,事实证明,Reactor的Mono
有一个toCompletableFuture
-方法,Spring MVC也可以使用它,而不是延迟结果。如果CompletableFuture
失败,将按预期引发异常
要失败,Mono
必须发出错误
,而不是空
:
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();
}
public Mono findOne(字符串id){
CompanyDetails结果=从某处检索(id);
返回单声道
.公正(结果)
.otherwiseIfEmpty(Mono.error(…);
}
@RequestMapping(value=“{id}”,method=RequestMethod.GET)
公共CompletableFuture getCompany(@PathVariable字符串id){
return companyService.findOne(id)
.toCompletableFuture();
}
现在好多了
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();
}