Add Guava Response Cache Spring Boot

To add simple response cacheing to a Spring Boot application.

 

  1. Add the guava dependency.
        <dependency>
          <groupId>com.google.guava</groupId>
          <artifactId>guava</artifactId>
          <version>18.0</version>
        </dependency>
    
  2. Configure the cache

    Annotate the config class

    import org.springframework.cache.annotation.EnableCaching;
    
    @EnableCaching
    

    Configure the bean

      /**
       * Response cache.
       */
      @Bean
      public CacheManager guavaCacheManager() {
        GuavaCacheManager guavaCacheManager = new GuavaCacheManager();
        guavaCacheManager.setCacheBuilder(CacheBuilder.newBuilder().expireAfterWrite(
            Long.parseLong(env.getProperty("request.cache.timeout", "600")), TimeUnit.SECONDS));
        return guavaCacheManager;
      }
    
    
  3. Annotate cacheable controller methods
    import org.springframework.cache.annotation.Cacheable;
    @Cacheable("mycache")