Irina Avram
Irina Avram

Reputation: 1532

Cancel rest request if response takes too long

I would like to cancel a REST request, if the response takes longer than 3 seconds, but I haven't managed to figure out how to do it.

So let's say I have a thread A:

@Override
public void run() {
    RestTemplate restTemplate = new RestTemplate();
    IsAliveMessage isAliveMessage = new IsAliveMessage(nodeInfo.getHostname(), nodeInfo.getPort());
    IsAliveResponse isAliveResponse = restTemplate.postForObject(
        "http://" + nodeInfo.getHostname() + ":" + nodeInfo.getPort() + "/node/isAlive",
         isAliveMessage,
         IsAliveResponse.class);
}

that makes a request and expects an answer from B:

@RequestMapping( value="/isAlive", method= RequestMethod.POST)
    public IsAliveResponse isAlive() throws ConnectException {
        try {
            Thread.sleep(100000);
            IsAliveResponse response = new IsAliveResponse("here here!" ,true);
            return response;
        } catch (Exception e) {
            Thread.currentThread().interrupt();
    }
}

B "sleeps" and doesn't answer, but A keeps waiting for that answer to come. How can I make A give up the waiting after a certain time span?

Thanks in advance

Upvotes: 2

Views: 2258

Answers (1)

ddarellis
ddarellis

Reputation: 3960

You can configure your RestTemplate to wait three seconds for response like this:

RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

private ClientHttpRequestFactory getClientHttpRequestFactory() {
    int timeout = 3000;
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
    new HttpComponentsClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(timeout);
    clientHttpRequestFactory.setReadTimeout(timeout);
    return clientHttpRequestFactory;
}

Upvotes: 2

Related Questions