Spring Boot and Caffeine Cache Integration

This article shows you how to configure Caffeine Cache in a Spring Boot application and also provides some important notes.

Thanh Tran
Nov 28, 2020 · 4 min read

Spring Cache Abstraction allows us to quickly make the application become cacheable. But it does not provide any real cache storage, it just provides cache features as ConcurrentMap which provided by the JDK.

Now, in this article, we are going to configure Caffeine Cache as cache storage for the Spring Application. Before jumping to the coding section, let’s have a quick intro about Caffeine Cache and Spring Cache Abstraction.

Caffeine Cache and Spring Boot
Caffeine Cache and Spring Boot
Photo by Alex Jones on Unsplash

Introduction to Caffeine Cache

Caffein is a high-performance Java 8 based caching library providing a near-optimal hit rate.

Caffeine Cache is similar to JDK ConcurrentMap but is not quite the same. A JDK ConcurrentMap persists all elements which we put to. Its elements still remain until we call the remove method to remove its element. We usually do these things by writing code. Unlike ConcurrentMap, a cache is generally configured to evict entries automatically, in order to constrain its memory footprint.

Caffeine provides flexible construction to create a cache with a combination of the following features:

  • automatic loading of entries into the cache, optionally asynchronously
  • size-based eviction when a maximum is exceeded based on frequency and recency
  • time-based expiration of entries, measured since last access or last write
  • asynchronously refresh when the first stale request for an entry occurs
  • keys automatically wrapped in weak references
  • values automatically wrapped in weak or soft references
  • notification of evicted (or otherwise removed) entries
  • writes propagated to an external resource
  • accumulation of cache access statistics

To improve integration, JSR-107 JCache and Guava adapters are provided in extension modules. JSR-107 standardizes a Java 6 based API to minimize vendor specific code at the cost of features and performance. Guava’s Cache is the predecessor library and the adapters provide a simple migration strategy.

Link to learn more about Caffeine Cache:

Introduction to Spring Cache Abstraction

I have already written an article about Spring Cache Abstraction. As a developer mindset, we should reuse code. So please read my old writing here:

Time to code: Integrate Caffeine Cache to Spring Boot

The idea for this demonstration is a simple REST service which allows us to retrieve book detail by its ISBN. In order to test the caching result, we need a simulator to simulate the slow speed of the network. Take a look at the code snippet below to see how the simulator looks like.

The image below shows the structure of our demo.

project structure: integat ecaffeine cache to spring boot application
project structure: integat ecaffeine cache to spring boot application

The main purpose of this demo is to show how to configure Caffeine Cache in a Spring Application so let have a quick view on the controller s, services, and the Book entities then we will dive into the cache integration section.

I have annotated EnableCaching at start-class. It’s required by the mechanism of Spring Caching Abstraction. By this time, the application already for caching feature but it has no actual cache storage. Currents cache storage is JDK ConcurrentMap.

The BookController: When we open up the web browser then send a request. The BookController will call bookService to get book information.

The Book entity

Caffeine Cache Integration

In order to build this demo, there are two necessary modules needed. They are spring-boot-starter-cache and spring-boot-starter-web. Of course, the caffeine must not be missing.

The spring-boot-starter-cache included spring-boot-starter and spring-context-support modules therefore we don't need to create the configuration classes and org.springframework.cache.CacheManager implementation as well as org.springframework.cache.Cache implementation for Caffeine cache(These are built-in classes created by the spring team. In case you really need customization you should consider creating a new one).

The spring-boot-starter-web allows us to create the REST service.

As I previously mentioned, the bookController calls the bookService to get book detail. The implement for BookService is where we put @Cacheable, @CachePut, @CacheEvict, etc. See how I implement the BookService at a simple level.

Basically, any request with a new isbn must wait for 3000 milliseconds by default before the book detail can be returned. If you want to increase the wait duration, just simply add a new line intoapplication.properties like this:

debug=true
demo.wait.duration=6000

Verify the integration result

The first thing we need to do is laugh the application. I usually directly laugh in the IDE. But we can also laugh by executing this maven command: mvn spring-boot:run

The CONDITIONS EVALUATION REPORT should be shown as an image below.

Image for post
Image for post

We also can make a request to http://localhost:8080/book/12 and wait for the book to be returned.

Great! Thank you all for your reading

Source demo: https://github.com/Programming-Sharing/spring-caching-demo/tree/spring-and-caffeine-cache-integration

Give me motivation

To get new article update please follow our publication or follow us on social

Facebook: https://www.facebook.com/programmingsharing

Twitter: http://twitter.com/progsharing

Programming Sharing

We write about programming. We share about programming.

By Programming Sharing

Get new articles update by signing up our newsletter Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Thanh Tran

Written by

Software Engineer, I am passionate about software development and love to share my knowledge with all of you.

Programming Sharing

The publication to share programming knowledge

Thanh Tran

Written by

Software Engineer, I am passionate about software development and love to share my knowledge with all of you.

Programming Sharing

The publication to share programming knowledge

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app