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")
    
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s