Sitemap

Member-only story

Using spring cache

2 min readSep 5, 2024

--

Sometimes a microservice needs to retrieve basic information to perform business logic like validations, limits, and even security restrictions. This information in some cases doesn’t change frequently and in a highly transactional application retrieving this data in every request causes bottlenecks, cost increases, and latency.

Using a Cache is a simple and efficient way to face these problems, the main purpose is to increase data retrieval performance by reducing the need to access the data.

This guide walks you through enabling caching on a Spring application using Ehcache.

Press enter or click to view image in full size
  1. Add the spring cache dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2. Enable Caching

@SpringBootApplication
@EnableCaching
public class LabSpringCacheApplication {

public static void main(String[] args) {
SpringApplication.run(LabSpringCacheApplication.class, args);
}
}
# CACHE
spring.cache.jcache.config=classpath:ehcache.xml

3. Add the annotation @Cacheable to the method that retrieves the information you want in the cache.

For testing purposes, there was added a variable called counter to get the number of invokes that the…

--

--

Marvin Díaz
Marvin Díaz

Written by Marvin Díaz

I've worked in software development since 2010, I enjoy using Linux and open source technologies.