0

I have several read-only resources in my Controller. I want to in-memory cache them, I'm not clear how to do it in Spring Boot. What I've done:

  • annotated main Application with @EnableCaching
  • annotated a resource with @Cacheable

@Cacheable
@RequestMapping(value = "/api/graph", method=RequestMethod.GET, produces = { "application/json"})
public @ResponseBody Iterable<Map<String, String>> graph() {
    return Repository.graph();
}

What am I missing? Since it's a read-only resource I guess I don't neet @CachePut am I right?

Obiouvsly I added spring-boot-starter-cache ad dependency in maven

alfredopacino
  • 2,979
  • 9
  • 42
  • 68

1 Answers1

0

Here are the steps to enable the Cache. For example i am using Google GuavaCacheManager for this purpose.

  1. Add dependency and Enable the caching by using annotation on Application class.

    <dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
    </dependency>
    
    @SpringBootApplication
    @EnableCaching
    public class Application extends SpringBootServletInitializer {
    }
    
  2. Expose the GuavaCacheManager as a bean in your Application class.

    @Bean
    public CacheManager cacheManager() {
    GuavaCacheManager cacheManager = new GuavaCacheManager();
    // Cache expires every day
    cacheManager.setCacheBuilder(CacheBuilder.newBuilder().expireAfterAccess(1, 
    TimeUnit.DAYS).expireAfterWrite(1, TimeUnit.DAYS)); 
    cacheManager.setCacheNames(Arrays.asList("findUser"));
    return cacheManager;
    }
    
  3. Mark the method as Cacheable so all the calls to this method first try to find the entry in Cache if not found then actually calls the method

    @Override
    @Cacheable("findUser")
    public User findUser(String username) {
    // biz logic to find the user and return the object
    return user;
    }
    
Kul Bhushan Prasad
  • 859
  • 3
  • 12
  • 19