Spring & Guava Cache

Check the excellent guide here about Cache in Spring. Below you can find similar code. Also check the official docs.

// compile ('org.springframework:spring-context-support:4.0.7.RELEASE')

@Configuration
@EnableCaching
public class CacheConfig implements CachingConfigurer {

	public final static String CACHE = "cache";

	private static final Logger LOGGER = LoggerFactory.getLogger(CacheConfig.class);

	@Bean
	@Override
	public CacheManager cacheManager() {
		LOGGER.info("Initializing simple Guava Cache manager.");
		SimpleCacheManager cacheManager = new SimpleCacheManager();
		GuavaCache discoveryCache = new GuavaCache(CACHE,
				CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES).build());
		cacheManager.setCaches(Arrays.asList(discoveryCache));
		return cacheManager;
	}

	@Bean
	@Override
	public KeyGenerator keyGenerator() {
		return new SimpleKeyGenerator();
	}

}
// mark method with @Cacheable annotation
@Component
public class CacheService {

	@Inject
	private BooksService bookService;

	@Cacheable(CacheConfig.CACHE)
	public List<Book> getBooks() {
		return bookService.getBooks();
	}
}

// You can clear cache like this
@Controller
@RequestMapping("/")
public class ClearCacheController {

	@CacheEvict(value = CacheConfig.CACHE, allEntries = true)
	@RequestMapping(value = "/clearCache", method = RequestMethod.GET)
	public ResponseEntity<String> clearCache() {
		return new ResponseEntity<String>("Cache Cleared", HttpStatus.OK);
	}
}

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