我正在使用 Spring Webflux 和 Spring boot 2,我的场景是这样的:
Controller
@GetMapping(path="/products")
public List<Products> getProducts(){
return serviceObj.getProducts();
}
服务类
public List<Products> getProducts(){
List<Products> products = null;
//Call 1 -> to repository class method returning Flux<Products>
repositoryObj.getProductsFlux();
//Call 2 -> To repository class method returning List<Products>
repositoryObj.getProductsNormal();
//Concat results from Call 1 & Call 2 and return List<Products>
return products;
}
如何在返回之前连接来自 Flux 和 normal 产品列表的结果? 没有 Reactive Controller 是否可行?
附言我不想对调用 1 获得的结果调用 .block() 和 CompleteableFuture
最佳答案
没有 .block()
就没有办法做到这一点如果你想返回 List<Products>
从那个方法。
您应该合并结果并返回 Flux<Products>
从这个方法到保持被动的方法。您可以使用 mergeWith
或 concatWith
示例:
public Flux<Products> getProducts(){
List<Products> productsNonFlux = repositoryObj.getProductsNormal();
Flux<Products> productsFlux = repositoryObj.getProductsFlux();
return productsFlux.mergeWith(Flux.fromIterable(productsNonFlux));
}
重要!
请记住,如果您的 repositoryObj.getProductsNormal()
正在使用 JDBC,那么此调用将阻塞线程池。
在这种情况下,请查看: Execute blocking JDBC call in Spring Webflux
关于spring-boot - 结合非阻塞和阻塞调用并在 Spring Webflux 中返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62462133/