membersound
membersound

Reputation: 86747

How to wait for WebClient response on timeout in Spring?

I have a WebClient that I want to stop and provide a fallback value after a certain timeout.

webClient.post()
    .uri(path)
    .bodyValue(body)
    .retrieve()
    .bodyToMono(type)
    .timeout(Duration.ofSeconds(15))
    .onErrorResume(ex -> Mono.just(provideFallbackValue())); //not only timeout, but any failure

Anyways, I would like to continue waiting for the response in another background thread in case of a TimeoutException (at least for let's say for another 60s), and still process the response then async.

Is that possible?

Upvotes: 0

Views: 2127

Answers (2)

Denise
Denise

Reputation: 1

You can use webClient.toFuture.get(15000, TimeUnit.MILLISECONDS) instead of setting the timeout on the Mono itself.

Upvotes: 0

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

What you can do is change the point of view of this code. Instead of wait for additional 60 seconds in another thread start immediately the new thread and work asynchronously.

If the answer from the second thread arrives in 15 seconds or less you can reply immediately. Otherwise, send the message related to the error, but you still have active the call until 60 seconds.


Here is a code that can do that:

private Future<YourClass> asyncCall() {
    ...
    // Put here the async call with a timeout of 60 seconds
    // This call can be sync because you are already in a secondary thread
}


// Main thread
try {
    Future<YourClass> future = executors.submit(() -> asyncCall());
    YourClass result = future.get(15, TimeUnit.SECOND);
    // Result received in less than 15 seconds
} catch (TimeoutException e) {
    // Handle timeout of 15 seconds
}

Upvotes: 1

Related Questions