Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement client side http caching like a browser?

I use a RESTFul service as a backend to my frontend. The service sets expires/etag/lastmodified headers on it's responses.

What I'm looking for is a client-side(favorably java) library which can fetch data from the service and cache it in a pluggable caching backend like ehcache.

What I also want to be able to do is automatically prime the cache using background worker threads as soon as an entry is invalidated. Also, it should be smart to do conditional GETs.

I've come across http://hc.apache.org/httpcomponents-client-ga/tutorial/html/caching.html

Is there any other library anyone knows about? Isn't this a fairly common problem?

like image 822
Sam Avatar asked Dec 12 '22 09:12

Sam


1 Answers

The 4.0+ version of the Apache HttpComponents library comes with HTTP 1.1 cache support. You can use this with the Spring RestTemplate restful client as follows:

    CacheConfig cacheConfig = new CacheConfig();  
    cacheConfig.setMaxCacheEntries(1000);
    cacheConfig.setMaxObjectSize(8192);

    HttpClient cachingClient = new CachingHttpClient(new DefaultHttpClient(), cacheConfig);

    ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(cachingClient);
    RestTemplate rest = new RestTemplate(requestFactory);
like image 83
Ricardo Gladwell Avatar answered Jan 13 '23 02:01

Ricardo Gladwell