Webflux WebClient 异步请求和处理 Mono [英] Webflux WebClient asynchronous Request and processing Mono

查看:428
本文介绍了Webflux WebClient 异步请求和处理 Mono的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to webflux and am not able to find the right material to continue with the implementation.

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

I want to issue a request and process the response asynchronously. In this case service call takes about 8-10 ms to respond, so we issue the request and continue doing other work, and look for the response when it is needed for further processing.

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

我们如何使这个调用在不同的线程上异步执行.(我尝试了使用 Schedulers.single/Scheuldes.parallel 的subscriberOn),但是直到调用 Mono.block() 才看到调用被执行.

How do we make this call execute asynchronously on a different thread.(I tried subscriberOn with Schedulers.single/ Scheuldes.parallel), but didn't see the call getting executed until Mono.block() is called.

我们如何实现?

  1. 我们希望这个调用在一个单独的线程上并行执行,所以当前线程可以继续其他工作
  2. 处理完成后,设置对上下文的响应
  3. 当前线程寻找响应时,如果服务还没有完成,阻塞直到调用完成

推荐答案

您不需要阻塞以使用响应.只需分配一个运算符来使用同一链中的响应.下面给出一个例子.

You don't need to block for consuming the response. Just assign an operator to consume the response in the same chain. An example is given below.

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() 方法的参数.

Alternatively you can provide a consumer as a parameter of the subscribe() method.

这篇关于Webflux WebClient 异步请求和处理 Mono的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆