Tuesday, 16 August 2016

Spring Cache

Spring can provide incredibly unobtrusive caching management through the use of spring's own @Cache annotations or through the use  JSR-107 JCache annotations. All that is needed, is to set up a cache manager within the applications context. There are some CacheManager provided by Spring out of the box such as EHCache, Guava and Redis.

Once again I have created a template project to get you stared here: https://github.com/rizvn/SpringCache

The template project uses EHCache as the cache implementation.

Firstly we need in configure caching through the use of @EnableCaching then configure a cache manager for the context. The spring configuration looks like below. The full code is here:

@EnableCaching //<---- This enables caching for the spring context
public class Config {

  //This is the cache manager that will be used for the context
  public CacheManager cacheManager() {
    EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();

    //ehcache.xml is under src/main/resources/ehcache.xml
    ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));

    return new EhCacheCacheManager(ehCacheManagerFactoryBean.getObject());


Once we have the configuration up and running all we have to do is annotate methods for which we want to cache response, using @Cacheble,  also to store shared cache config information for classes, use @CacheConfig. Below is an example of a cached response. The full code is here

@CacheConfig(cacheNames = "calculator_cache") //<-- default cache where results will be cached
public class SlowCalculator {

  @Cacheable //<-- indicates that the result will be cached so, second call with same arguments will not wait 5000ms
  public Double calculateHypotenuse(int a, int b) {
    System.out.println("Calculating hypotenuse...");
    return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));

  private void sleep(long seconds) {
    try {
    } catch (Exception e) {
      throw new IllegalStateException(e);

No comments:

Post a Comment