Guava Cache

Kevin FOO
Jan 15, 2023

--

Spring Boot starter cache is able to cache REST API response but expiring the cache will be troublesome to implement. Guava cache will solve this problem. Example below is a prototype from scratch on how to implement Guava cache.

Spring initializer
Add dependencies
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
Project folder structure

Below are the codes for
1. Book.java
2. BookController.java
3. CacheStore.java
4. CacheStoreBeans.java

I added a 2 seconds delay to simulate slow record retrieval from database.

I set the cache duration to 5 seconds.

By running a simulation in Bash. It is obvious that the first call took 2 seconds and subsequent calls are less than 1 second. Once the cache expires, it took 2 seconds again.

< Back to all the stories I had written

--

--

Kevin FOO
Kevin FOO

Written by Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.