我有一个我的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);
那么我没有任何回应。为什么需要等待回复?
您的代码正在使用,Thread.sleep(1000);
因为您在一段时间内阻止了父线程,并且在这段时间内您从WebClient获得了响应。
WebClient是非阻塞HTTP客户端。由于您需要从mySimpleTestMethod
方法中返回响应,因此需要进行阻塞,直到使用检索响应为止Mono#block()
。
String responseStr = result.block();
然后您可以返回响应。
另外,请注意,在下面的代码中,您正在调用toString
Disposable类型(LambdaMonoSubscriber),LambdaMonoSubscriber不会覆盖toString
方法,因此,您是reactor.core.publisher.LambdaMonoSubscriber@60b71e8f
从Object类的toString方法获取字符串值()。
String responseStr = result.subscribe(response -> System.out.println(response)).toString();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句