Skip to content

Lab M12P01

Spring Cache abstraction enables to use caching feature in your application. If you want to add caching for instance on service layer of your application, you can use declarative caching definition. Spring Boot autoconfiguration defines appropriate Cache Manager and resolution for supported cache backend automatically. Let's try [Ehcache](https://www.ehcache.org/.

  1. Ensure the org.springframework.boot:spring-boot-starter-cache starter is defined in build.gradle.

  2. Enable caching with the @EnableCaching annotation on Application class

  3. There is ehcache.xml file prepared in the main resources folder. Now add configuration into application.properties.

      spring.cache.jcache.config=classpath:ehcache.xml
    
  4. The ite.librarymaster.service.LibraryServiceImpl provides CRUD services. As Book entity is quite static data structure, you can add caching to improve performance of the getBook() method. Use @Cacheable(cacheNames = "books") annotation, where 'books' is the cache name configured in the ehcache.xml file.

      // Examples
      @Cacheable(cacheNames = "books")
      @Cacheable(cacheNames = "books", key="#id")
      @Cacheable(cacheNames = "books", condition="#id != null ? #id%2 == 0 : true") 
    

    When caching is in place, start the Application a nd try to get Book by ID via rest api. You can try conditional caching feature as well.

      curl --location 'http://localhost:8080/api-book/books/1'
    
  5. You can use the @CachePut annotation to put object into cache after save or update operations. Try it on the saveBook() method of the ite.librarymaster.service.LibraryServiceImpl service. Use newly generated ID of the Book as cache Key.

       @CachePut( cacheNames = "books", key = "#result.id", condition = "#result.id != null" )
    
  6. The object eviction from cache can be configured on caching backend using TTL configuration. You can also evict cache using @CacheEvict annotation.

      @CacheEvict(cacheNames = "books", allEntries = true)