[英]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.