To add simple response cacheing to a Spring Boot application.
- Add the guava dependency.
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency>
- 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; }
- Annotate cacheable controller methods
import org.springframework.cache.annotation.Cacheable; @Cacheable("mycache")