Home > Mobile >  Stop / Interrupt the long running request
Stop / Interrupt the long running request

Time:08-18

We have a scenario- Service A calls Service B by a HTTP GET request.

Service A ---> Service B

Service B at times, takes more than 2 minutes to return the result since it sometimes has to process a lot.

I want to know how to do this by Spring Boot Rest Template.

Service A is using Spring Boot Rest Template to call Service B. How can RestTemplate be programmed to kill a request when Service B takes more time than specified ? What I want to know is how can I stop/Interrupt the request in Service A if it takes more than 30 seconds to complete.

Also Is it possible to use @Retry annotation of Resilience4J to retry if we do not get a response within 30 seconds. Service B is notoroious , there are high chances when we retry , it gives a reponse quicker than 2 minutes.

CodePudding user response:

For such scenario, I would suggest you to customise your restTemplate bean something like below:

@Bean
RestTemplate restTemplate() {

CloseableHttpClient client=HttpClients.createDefault();

HttpComponentsClientHttpRequestFactory req
        =new HttpComponentsClientHttpRequestFactory(client);
        req.setConnectionRequestTimeout(30000);
        req.setReadTimeout(30000);
        req. setConnectTimeout(30000);
return new RestTemplate(req);
}

So basically, you are setting timeouts in your restTemplate so that it will timeout & don't wait for default timeout setting.

CodePudding user response:

What you can do is adding a readTimeout(). For more info about readTimeout and connectionTimeout check this link.

For setting the readTimeout in RestTemplate take a look at this answer: https://stackoverflow.com/a/45715580/8363012

  • Related