Spring WebFlux – Why I have to wait for WebClient response?

Tags: , ,



I have a my WebClient class as per below:

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;
    }

}

After execution I get this on my console:

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

Question: If I comment Thread.sleep(1000); then I dont get any response. Why do I need to wait for the response?

Answer

Your code is working with Thread.sleep(1000); because you are blocking the parent thread for some time and within this time you are getting a response back from WebClient.

WebClient is a non-blocking HTTP client. As you need to return the response back from the mySimpleTestMethod method, you need to block until you retrieve the response using Mono#block().

String responseStr = result.block();

and then you can return the response back.

Also, note that in the below code you are calling toString on Disposable type (LambdaMonoSubscriber), LambdaMonoSubscriber doesn’t override toString method, as a result, you are getting string value (reactor.core.publisher.LambdaMonoSubscriber@60b71e8f) from toString method of the Object class.

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


Source: stackoverflow