spring-boot - 结合非阻塞和阻塞调用并在 Spring Webflux 中返回结果

标签 spring-boot spring-webflux project-reactor nonblocking spring-reactive

我正在使用 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/

相关文章:

spring-boot - 更正应用程序的类路径,以使其包含org.elasticsearch.client.IndicesClient的单个兼容版本

Spring 5 WebFlux Mono 和 Flux

java - Spring webflux Controller : consuming POJO vs Mono?

java - Spring 套应用中的 yarn 配置

Spring REST Controller 不处理 gzip 压缩输入

java - 无法在Spring Boot中实现Drools KieSession持久化

spring - Spring boot 2.0 响应式(Reactive) webflux 配置中的默认线程数

spring - 使用 Spring WebFlux 客户端使用 REST 端点时出错

spring-webflux - Spring 2.0 WebFlux : Merge multiple Mono<String> , 其中 string 是转换为 string 的 json,转换为单个 Flux<String>

project-reactor - 在计划任务中使用 Flux