Adding caching annotations

The next step is to add the caching annotations, indicating when something needs to be added or removed from the cache. The following snippet shows an example:

    @Component
public class ExampleRepository implements Repository {
@Override
@Cacheable("something-cache-key")
public Something getSomething(String id) {
//Other code
}
}

Some of the annotations that are supported are as follows:

  • Cacheable: This is used to cache the result of a method invocation. The default implementation constructs the key based on the parameters passed to the method. The method will not be invoked if the value is found in the cache.
  • CachePut: This is similar to @Cacheable. A significant difference is that the method is always invoked and the result is put in a cache.
  • CacheEvict: This triggers an evict for a specific element from the cache. Typically done when an element is deleted or updated.

A few other important things to note about Spring caching are as follows:

  • The default cache used is ConcurrentHashMap.
  • The Spring caching abstraction is JSR-107 compliant.
  • Other caches that can be auto configured include Ehcache, Redis, and Hazelcast.

Spring Boot Cache starter makes it easy to integrate caching into your application with simple easy-to-use annotations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset