Spring WebFlux-为什么我必须等待WebClient响应?

阿杰·库玛(Ajay Kumar)

我有一个我的WebClient类,如下所示:

public class WebClientSample {
    
    public static void main(String[] args) throws InterruptedException {
        System.out.println(mySimpleTestMethod());
    }

    public static String mySimpleTestMethod() throws InterruptedException {
        String uri = "http://localhost:8080/some/cool/api/here";
        WebClient webClient = WebClient.create(uri);
        Mono<String> result = webClient
                .get()
                .headers(headers -> headers.setBasicAuth("admin", "secret"))
                .retrieve()
                .bodyToMono(String.class);
        String responseStr = result.subscribe(response -> System.out.println(response)).toString();
        Thread.sleep(1000);
        return responseStr;
    }

}

执行后,我在控制台上得到了这个:

{"some":{"cool":json,"response":{"foo":"bar",...}}}
reactor.core.publisher.LambdaMonoSubscriber@60b71e8f

问题:如果我发表评论,Thread.sleep(1000);那么我没有任何回应。为什么需要等待回复?

戈文达·萨哈雷(Govinda Sakhare)

您的代码正在使用,Thread.sleep(1000);因为您在一段时间内阻止了父线程,并且在这段时间内您从WebClient获得了响应。

WebClient是非阻塞HTTP客户端。由于您需要从mySimpleTestMethod方法中返回响应,因此需要进行阻塞,直到使用检索响应为止Mono#block()

String responseStr = result.block();

然后您可以返回响应。

另外,请注意,在下面的代码中,您正在调用toStringDisposable类型(LambdaMonoSubscriber),LambdaMonoSubscriber不会覆盖toString方法,因此,您是reactor.core.publisher.LambdaMonoSubscriber@60b71e8f从Object类的toString方法获取字符串值()。

String responseStr = result.subscribe(response -> System.out.println(response)).toString();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Spring WebFlux WebClient:延迟执行

Spring WebFlux WebClient处理ConnectTimeoutException

Spring Webflux非阻塞响应

在Spring Webflux中捕获响应

Spring WebFlux 和 WebClient 更改错误响应

Spring Webflux - 基于 TLSv1.2 的 WebClient

How to set a timeout in Spring 5 WebFlux WebClient

使用WebClient Spring WebFlux的多个请求

Spring Webflux 如何等待 webhook

Spring WebFlux没有流式响应

如何使用 Spring Webflux 返回 GZIP 响应?

如何获得Spring的WebFlux发出响应

Spring Webflux:我的 JAR 中的 FileNotFoundException

在Spring Webflux中处理条件响应的正确方法是什么

Spring @Async与Spring WebFlux

为什么在Spring 5 webflux中有HandlerFunctions?

为什么Spring Webflux默认选择码头然后失败?

为什么Spring Webflux仅并行接受256个请求?

Spring WebFlux MockServerRequest为什么不允许空的主体?

为什么带有响应式Webflux的Spring Cloud Contract要求EXPLICIT测试模式

在将响应返回给调用方时,如何注销对Spring WebFlux WebClient请求的失败响应的主体?

如何在 Spring Webflux WebClient 中处理令牌刷新

Spring Webflux WebClient将文件发布到客户端

Spring WebFlux WebClient-如何解决400错误请求

使用spring-webflux WebClient测试虚拟时间的问题

对于Spring WebFlux的WebClient,如何捕获Netty的异常(例如ProxyConnectException)

在高负载下测试spring webflux Webclient的问题

Spring WebFlux WebClient挂起,Mono.timeout无法捕获它

配置Spring WebFlux WebClient使用自定义线程池