Caching data

Now that we have enabled caching, we can add the @Cacheable annotation to the methods where we want to cache the data. The following code snippet shows how to enable caching on retrieveTodos:

    @Cacheable("todos")
public List<Todo> retrieveTodos(String user) {

In the preceding example, the todos for a specific user are cached. On the first call to the method for a specific user, the todos will be retrieved from the service. On subsequent calls for the same user, the data will be returned from the cache.

Spring also provides conditional caching. In the following snippet, caching is only enabled if the specified condition is satisfied:

    @Cacheable(cacheNames="todos", condition="#user.length < 10”)
public List<Todo> retrieveTodos(String user) {

Spring also provides additional annotations to evict data from the cache and add some custom data to cache. A few important ones are listed here:

  • @CachePut: Used to explicitly add data to the cache
  • @CacheEvict: Used to remove stale data from the cache
  • @Caching: Allows multiple nested @Cacheable, @CachePut, and @CacheEvict annotations to be used on the same method
..................Content has been hidden....................

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