javaspringcachingspring-bootgoogle-guava-cache

Facing issue with Guava Cache


I'm using Google Guava Cache + Spring cache abstraction for caching purpose. I'm trying to make use of Guava's Loading Cache interface for the same.

I know Spring provides support for Guava Cache, but I was wondering whether I can make use of spring's cacheable annotation alongwith Loading Cache?

Basically I wanted to keep the business layer separate from the Cache.

Kindly help. Thanks.


Solution

    1. Guava Cache is deprecated. If you'd existing code, that'd be another matter, but for new code, use Caffeine.

    2. Put a @Cacheable("myCacheName") on the method that you want to cache the return value for.

    3. Put a @EnableCaching on your application class if using Spring Boot, otherwise on some @Configuration class.

    4. Set the spec in application.properties if using Spring Boot, like so: spring.cache.caffeine.spec=maximumSize=10000,expireAfterWrite=5m. If not using Boot, use @PropertySources annotation on the same class as in #3 above.

    5. Add org.springframework.boot:spring-boot-starter-cache and com.github.ben-manes.caffeine:caffeine to your build file. If not using Boot, you'll need to set up the dependencies differently.

    You're done.