Webflux WebClient异步请求和处理Mono

时间:2019-01-09 19:33:17

标签: reactive-programming spring-webflux project-reactor

我是webflux的新手,无法找到合适的材料来继续实施。

我要发出请求并异步处理响应。在这种情况下,服务调用大约需要8到10毫秒来响应,因此我们发出请求并继续进行其他工作,并在需要进一步处理时寻找响应。

Mono<Map<String,Price>> resp = webClient.post()
.uri("/{type}",isCustomerPricing ? "customer" : "profile")
.body(Mono.just(priceDetailsRequest),PriceDetailsRequest.class)
.retrieve().bodyToMono(customerPriceDetailsType);

我们如何使此调用在另一个线程上异步执行(我在Scheduler.single / Scheuldes.parallel上尝试了SubscriberOn,但直到调用Mono.block()时才看到该调用被执行。

>

我们如何实现?

  1. 我们希望此调用在单独的线程上并行执行,因此 当前线程可以继续其他工作
  2. 处理完成后,将响应设置为上下文
  3. 当当前线程寻找响应时,如果服务还没有 完成,阻止直到通话结束

1 个答案:

答案 0 :(得分:0)

您不需要阻塞即可使用响应。只需分配一个运算符以使用同一链中的响应即可。下面是一个示例。

Mono<Map<String,Price>> resp = webClient.post()
        .uri("/{type}",isCustomerPricing ? "customer" : "profile")
        .body(Mono.just(priceDetailsRequest),PriceDetailsRequest.class)
        .retrieve()
        .bodyToMono(CustomerPriceDetailsType.class)
        .map(processor::responseToDatabaseEntity) // Create a persistable entity from the response
        .map(priceRepository::save)               // Save the entity to the database
        .subscribe();                             //This is to ensure that the flux is triggered.

或者,您可以提供使用者作为subscribe()方法的参数。