1

Below is our call to a third party service:

try {
    ResponseEntity<String> response = new RestTemplate().exchange(
                        requestUrl,
                        HttpMethod.POST,
                        new HttpEntity<String>(null, new HttpHeaders()),
                        String.class);
    // Log the response received (and request sent) 
    log.info(String.format("3rd party response: %s for request: %s" + response, requestUrl));
} catch (CustomTimeoutException e) {
    log.error(String.format("Call to 3rd party with %s failed with: %s", requestUrl, e));
}

If the requested service is not available, it takes 30 seconds to timeout. We have no control over their timeout time, so we'd like to throw, catch and handle a custom exception if we don't hear back in 3 seconds.

Not very experienced with threading so a concrete example of how this specific code would fit into the solution would be greatly appreciated.

Bradley D
  • 2,333
  • 1
  • 15
  • 19

1 Answers1

1

We have no control over their timeout time

Do not care about the server timeouts. As an HTTP client, you can define your own timeouts, on two distinct levels:

  • a connection timeout : how long max to reach the target server
  • a read timeout : allowing you to give up after a certain amount of time (and potentially earlier than the server will abort) in case the HTTP response does not come

See Spring doc on how to configure these two timeouts.

TacheDeChoco
  • 3,683
  • 1
  • 14
  • 17