Skip to content

spring-guides/gs-caching

This guide walks you through the process of enabling caching on a Spring managed bean.

What You Will Build

You will build an application that enables caching on a simple book repository.

Starting with Spring Initializr

You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.

To manually initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.

  2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.

  3. Click Dependencies and select Spring cache abstraction.

  4. Click Generate.

  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

Note
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.
Note
You can also fork the project from Github and open it in your IDE or other editor.

Create a Book Model

First, you need to create a simple model for your book. The following listing (from src/main/java/com/example/caching/Book.java) shows how to do so:

link:initial/src/main/java/com/example/caching/Book.java[role=include]

Create a Book Repository

You also need a repository for that model. The following listing (from src/main/java/com/example/caching/BookRepository.java) shows such a repository:

link:initial/src/main/java/com/example/caching/BookRepository.java[role=include]

You could have used {SpringData}[Spring Data] to provide an implementation of your repository over a wide range of SQL or NoSQL stores. However, for the purpose of this guide, you will simply use a naive implementation that simulates some latency (network service, slow delay, or other issues). The following listing (from src/main/java/com/example/caching/SimpleBookRepository.java) shows such a repository:

link:initial/src/main/java/com/example/caching/SimpleBookRepository.java[role=include]

simulateSlowService deliberately inserts a three-second delay into each getByIsbn call. Later on, you will speed up this example with caching.

Using the Repository

Next, you need to wire up the repository and use it to access some books. The following listing (from src/main/java/com/example/caching/CachingApplication.java) shows how to do so:

link:initial/src/main/java/com/example/caching/CachingApplication.java[role=include]

You also need a CommandLineRunner that injects the BookRepository and calls it several times with different arguments. The following listing (from src/main/java/com/example/caching/AppRunner.java) shows that class:

link:complete/src/main/java/com/example/caching/AppRunner.java[role=include]

If you try to run the application at this point, you should notice that it is quite slow, even though you are retrieving the exact same book several times. The following sample output shows the three-second delay that our (intentionally awful) code created:

2014-06-05 12:15:35.783  ... : .... Fetching books
2014-06-05 12:15:40.783  ... : isbn-1234 -->Book{isbn='isbn-1234', title='Some book'}
2014-06-05 12:15:43.784  ... : isbn-1234 -->Book{isbn='isbn-1234', title='Some book'}
2014-06-05 12:15:46.786  ... : isbn-1234 -->Book{isbn='isbn-1234', title='Some book'}

We can improve the situation by enabling caching.

Enable caching

Now you can enable caching on your SimpleBookRepository so that the books are cached within the books cache. The following listing (from src/main/java/com/example/caching/SimpleBookRepository.java) shows the repository definition:

link:complete/src/main/java/com/example/caching/SimpleBookRepository.java[role=include]

You now need to enable the processing of the caching annotations, as the following example (from src/main/java/com/example/caching/CachingApplication.java) shows how to do:

link:complete/src/main/java/com/example/caching/CachingApplication.java[role=include]

The @EnableCaching annotation triggers a post-processor that inspects every Spring bean for the presence of caching annotations on public methods. If such an annotation is found, a proxy is automatically created to intercept the method call and handle the caching behavior accordingly.

The post-processor handles the @Cacheable, @CachePut and @CacheEvict annotations. You can refer to the Javadoc and the reference guide for more detail.

Spring Boot automatically configures a suitable CacheManager to serve as a provider for the relevant cache. See the Spring Boot documentation for more detail.

Our sample does not use a specific caching library, so our cache store is the simple fallback that uses ConcurrentHashMap. The caching abstraction supports a wide range of cache libraries and is fully compliant with JSR-107 (JCache).

Test the Application

Now that caching is enabled, you can run the application again and see the difference by adding additional calls with or without the same ISBN. It should make a huge difference. The following listing shows the output with caching enabled:

2016-09-01 11:12:47.033  .. : .... Fetching books
2016-09-01 11:12:50.039  .. : isbn-1234 -->Book{isbn='isbn-1234', title='Some book'}
2016-09-01 11:12:53.044  .. : isbn-4567 -->Book{isbn='isbn-4567', title='Some book'}
2016-09-01 11:12:53.045  .. : isbn-1234 -->Book{isbn='isbn-1234', title='Some book'}
2016-09-01 11:12:53.045  .. : isbn-4567 -->Book{isbn='isbn-4567', title='Some book'}
2016-09-01 11:12:53.045  .. : isbn-1234 -->Book{isbn='isbn-1234', title='Some book'}
2016-09-01 11:12:53.045  .. : isbn-1234 -->Book{isbn='isbn-1234', title='Some book'}

In the preceding sample output, the first retrieval of a book still takes three seconds. However, the second and subsequent times for the same book are much faster, showing that the cache is doing its job.

Summary

Congratulations! You’ve just enabled caching on a Spring managed bean.

About

Caching Data with Spring :: Learn how to cache data in memory with Spring

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published