2

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

1 Answer 1

2

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, connectTimeout occurs when establishing connection takes longer than three seconds, and readTimeout occurs when client doesn't receive any data from server for three seconds. So basically servers response with this configuration can take ages if it serves data slow but with breaks shorter than three seconds

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.