Spring Boot and Cache

A quick intro to caching and applying it to Spring boot applications.

Why cache?

In Software applications, it is required to provide users with up-to-date information but we could have some scenarios in which the data doesn't change very often.

In that scenario, we could implement caching which would provide the following benefits:

  • Faster UI rendering since the roundtrip time to the server is decreased

  • Reduced cost as some services are charged based on the number of requests

  • Reduces the dependency on external services

Caching in Spring framework?

Spring framework provides support for caching. The cache abstraction provided doesn't provide an actual store and we may add it explicitly.

Spring supports different cache providers such as Redis, Caffeine, Hazelcast, etc. You can also disable caching if needed.

Enabling Cache in Spring boot:

In the pom file add the dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>2.4.0</version>
</dependency>

In the main method add the @EnableCaching annotation

@SpringBootApplication
@EnableCaching
public class Main {
}

Add Cache to a function

To add caching to a particular method, add the @Cacheable annotation. A name has to be given to the cache.

@Cacheable("courses")
HashSet<Course> findAllCourse();

Clear Cache

To clear the cache using the @CacheEvict annotation. For example when a new record is inserted

@CacheEvict(value="courses", allEntries=true)
void addCourse(Course course);

Conclusion

In this short article, we viewed how easy it is to implement caching using spring. When multiple instances of the application are running we would have to use a distributed caching solution such as Redis Cache.