【发布时间】:2018-01-05 12:49:35
【问题描述】:
目前我开始使用 Spring + 反应式编程。我的目标是从长时间运行的方法(在数据库上轮询)在 REST 端点中返回结果。我被困在api上。我根本不知道如何在我的FooService.findFoo 方法中将结果返回为Mono。
@RestController
public class FooController {
@Autowired
private FooService fooService;
@GetMapping("/foo/{id}")
private Mono<ResponseEntity<Foo> findById(@PathVariable String id) {
return fooService.findFoo(id).map(foo -> ResponseEntity.ok(foo)) //
.defaultIfEmpty(ResponseEntity.notFound().build())
}
...
}
@Service
public class FooService {
public Mono<Foo> findFoo(String id) {
// this is the part where I'm stuck
// I want to return the results of the pollOnDatabase-method
}
private Foo pollOnDatabase(String id) {
// polling on database for a while
}
}
【问题讨论】:
-
这与我的问题有关吗?如果是这样,我不明白。
-
是的。我的意思是从你的服务类 findFoo 方法,你不能像
return Mono.just(pollOnDatabase(id)) -
谢谢一百万,这就是我想要的。
-
你使用的是数据库,也就是JDBC,这意味着你基本上是把口红涂在猪身上。 JDBC 是阻塞的且不响应的,因此您基本上一无所获。您可以在不使用异步结果的反应式编程的情况下实现同样的效果。
-
确实如此。感谢您指出这一点。
标签: spring-mvc spring-boot reactive-programming