HTTP Cache

Caching is a powerful mechanism to increase application performance and to improve user-experience. There exist caches at each level of the application, i.e. at the database, in the application server and at the client. It generally applies, the closer the data can be kept at the client, the better the performance. However, not all caches are equally well known. The http cache is a browser cache  with which data is directly kept at the client and is probably the fewest known cache. The following shows how to configure this cache with a simple Restful service with Spring Boot. See Increasing Application Performance with HTTP Cache Headers for a more detailled description of the http cache.

The following code snippet shows a simple RestController which returns „Hello World!“ two seconds later after the service has been called. Furthermore, the Cache-Control in the http header is set to max-age =5. This tells the web browser that this response can be kept for 5 seconds in the cache before it is discarded.


@RestController
public class HelloController {
@RequestMapping("/hello")
public String sayHello(HttpServletResponse response) throws InterruptedException {
response.setHeader("Cache-Control", "max-age=5");
TimeUnit.SECONDS.sleep(2);
return "Hello World!";
}
}

view raw

HelloController

hosted with ❤ by GitHub

That’s all. If you start the application and call http://localhost:8080/hello you will see „Hello World!“ after a delay of two seconds. If you call the service again, the reponse appears immediately as it is was cached this time. This works quite well with IE. However, Chrome automatically sets Cache-control: max-age=0 on the request’s header if you’re refrehsing the page. This obviously prevents the data from being cached. To test the correct caching behavior in Chrome anyway, one can create a dummy HTML page with a link to the service and then calling the service via this link. If you are opening the dev tools in your browser and inspect the response headers, you should see that the Cache-Control is correctly set:

httpcache
Response header

If Spring Security is enabled and you are experiencing problems with the cache, try to disable the cache-control header in the security configuration:


@Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/hello").permitAll()
.anyRequest().authenticated();
http.headers().cacheControl().disable();
}
}

view raw

SecurityConfig

hosted with ❤ by GitHub

The whole project can be found here: http-cache-demo

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden /  Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s