3
Aug 18

I have tried finding an example implementation for this online and to my surprise nothing I found did the trick. Therefore I am sharing my solution here in case anyone else runs into this in the future. I am new to Spring Boot and it's possible there are other, better ways to go about it, but something is better than nothing.

The problem

You want to make an http call from your server to another server, but you don't want to block your thread waiting for the other server to respond. How do you do that in Spring Boot?

The solution

WebClient does the trick. Check out the following implementation:

@Async
public CompletableFuture<String> loadDataFromAPI() {
    CompletableFuture<String> future = new CompletableFuture<>();
    try {
        WebClient
        .create("https://reqres.in/")
        .get()
        .uri("/api/users?page=2")
        .retrieve()
        .bodyToMono(String.class)
        .subscribe(future::complete);
    } catch (Exception e) {
        LOGGER.error("Failed loading data from API", e);
    }
    return future;
}

I won't go over this code line by line as it should be self explanatory. There is no error handling here, I just wanted to provide a barebone working example for you to build upon.

Leave a Reply