[英]Spring WebFlux - Why I have to wait for WebClient response?
我有一个我的 WebClient class,如下所示:
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);
然后我没有得到任何回应。 为什么我需要等待响应?
您的代码正在使用Thread.sleep(1000);
因为您将父线程阻塞了一段时间,并且在这段时间内您从 WebClient 收到了响应。
WebClient 是一个非阻塞的 HTTP 客户端。 由于您需要从mySimpleTestMethod
方法返回响应,因此您需要阻止,直到您使用Mono#block()
检索响应。
String responseStr = result.block();
然后您可以返回响应。
另外,请注意,在下面的代码中,您在 Disposable 类型(LambdaMonoSubscriber)上调用toString
,LambdaMonoSubscriber 不会覆盖toString
方法,因此,您从 toString 方法获取字符串值( reactor.core.publisher.LambdaMonoSubscriber@60b71e8f
) Object class 的。
String responseStr = result.subscribe(response -> System.out.println(response)).toString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.