Here is a complete example of setting up a Guava cache in Spring. I used Guava over Ehcache because it is a bit lighter and the configuration seemed to me more direct.
Import Maven Dependencies
Add these dependencies to your maven mam file and do the cleanup and packages. These files are helper methods of Guava dep and Spring for use in CacheBuilder.
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.1.7.RELEASE</version> </dependency>
Configure cache
You need to create a CacheConfig file to configure the cache using the Java configuration.
@Configuration @EnableCaching public class CacheConfig { public final static String CACHE_ONE = "cacheOne"; public final static String CACHE_TWO = "cacheTwo"; @Bean public Cache cacheOne() { return new GuavaCache(CACHE_ONE, CacheBuilder.newBuilder() .expireAfterWrite(60, TimeUnit.MINUTES) .build()); } @Bean public Cache cacheTwo() { return new GuavaCache(CACHE_TWO, CacheBuilder.newBuilder() .expireAfterWrite(60, TimeUnit.SECONDS) .build()); } }
Annotate method for caching
Add the @Cacheable annotation and pass the cache name.
@Service public class CachedService extends WebServiceGatewaySupport implements CachedService { @Inject private RestTemplate restTemplate; @Cacheable(CacheConfig.CACHE_ONE) public String getCached() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> reqEntity = new HttpEntity<>("url", headers); ResponseEntity<String> response; String url = "url"; response = restTemplate.exchange( url, HttpMethod.GET, reqEntity, String.class); return response.getBody(); } }
Here you can see a more complete example with annotated screenshots: Guava Cache in Spring
anataliocs Aug 10 '15 at 18:37 2015-08-10 18:37
source share