Akshay
Akshay

Reputation: 1817

Stop / Interrupt the long running request

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.

Upvotes: 1

Views: 943

Answers (2)

Maarouf Yassine
Maarouf Yassine

Reputation: 21

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

Upvotes: 0

Ashish Patil
Ashish Patil

Reputation: 4604

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.

Upvotes: 1

Related Questions