Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop org.springframework.web.client.RestTemplate caching the response?

In my Spring-boot project for REST HTTP calls I am using org.springframework.web.client.RestTemplate.

The problem is that it is caching the response, meaning that when I call it for the first time I get back the right response, but when I update data on server related to current API and when I call same API for the second time it still returns me the old response, so it is probably taking the ResponseEntity<T> from cache? I am not sure.. How to get the latest version of the response each time I call same API?

Here is how I make HTTP call

public <T> ResponseEntity<T> doQueryApi(String url, HttpMethod httpMethod, Object anyObject, HttpHeaders requestHeaders, Class<T> responseType) throws RestClientException {

        HttpEntity requestEntity = new HttpEntity(anyObject, requestHeaders);
        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, requestEntity, responseType);
        return responseEntity;
    }
}
like image 463
Renat Gatin Avatar asked Jan 08 '16 20:01

Renat Gatin


People also ask

What is Cache Control in Spring boot?

By using cache control headers effectively, we can instruct our browser to cache resources and avoid network hops. This decreases latency, and also the load on our server. By default, Spring Security sets specific cache control header values for us, without us having to configure anything.

How do you set the interceptor on a RestTemplate?

Setting up the RestTemplate For instance, if we want our interceptor to function as a request/response logger, then we need to read it twice – the first time by the interceptor and the second time by the client. The default implementation allows us to read the response stream only once.

Should I use WebClient instead of RestTemplate?

Compared to RestTemplate , WebClient has a more functional feel and is fully reactive. Since Spring 5.0, RestTemplate is deprecated. It will probably stay for some more time but will not have major new features added going forward in future releases. So it's not advised to use RestTemplate in new code.


1 Answers

You can try force no-caching requests in request headers this way:

// Force the request expires
requestHeaders.setExpires(0);
// Cache-Control: private, no-store, max-age=0
requestHeaders.setCacheControl("private, no-store, max-age=0");

I had similiar problem and it worked fine.

like image 78
Jorge Avatar answered Sep 22 '22 11:09

Jorge