1. Introduction to Caching
Caching is the process of temporarily storing the results of operations to reduce the need for recomputation or retrieval of data from the original source. When a request arrives, the system checks if the data is already in the cache. If so, it returns the data from the cache without performing the operation or query again. This helps to reduce the load on the system and improve response time.
Benefits of caching:
+ Reduced response time : Retrieving data from the cache is faster than recomputing or retrieving it from a database.
+ Reduced system load : Decreases the number of queries to a database or external service.
+ Cost savings : Reduces resource usage and costs for external services."
2. Caching in Spring Boot
Spring Boot offers a streamlined approach to caching through the spring-boot-starter-cache dependency. By leveraging this dependency, you can effortlessly set up and implement caching within your application. This guide will walk you through the configuration and usage of caching in Spring Boot.
2.1. Adding Dependencies
Pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
Build.gradle:
implementation 'org.springframework.boot:spring-boot-starter-cache'
2.2 Cache Configuration
Spring Boot supports various cache backends such as ConcurrentHashMap, Ehcache, Redis, Hazelcast, and more. You can configure the cache backend in your application's configuration file.
Example of configuring cache with Ehcache:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
2.3 Creating the Ehcache Configuration File
Creating the Ehcache Configuration File: Create a configuration file named ehcache.xml in the src/main/resources directory:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.ehcache.org/v3"
xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/v3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<cache alias="exampleCache">
<key-type>java.lang.String</key-type>
<value-type>java.lang.String</value-type>
<heap unit="entries">100</heap>
</cache>
</config>
2.4 Spring Boot configuration:
spring:
cache:
type: ehcache
2.5 Enable cache
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfig {
}
3. Using Caching in Spring Boot
3.1 Main Annotations:
@Cacheable : This annotation is used to mark a method whose result will be stored in the cache. If the data already exists in the cache, the method will not be executed, and the data will be returned from the cache instead.
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ExampleService {
@Cacheable("exampleCache")
public String getExpensiveData(String param) {
return "Expensive Data";
}
}
@CachePut is an annotation that instructs the caching framework to update the cache with the result of the annotated method. Regardless of whether the cache already contains a value for the given key, the method will be executed, and its return value will be stored in the cache. This ensures that the cache always reflects the most recent data, improving application performance by reducing the need to repeatedly execute the same logic.
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
@Service
public class ExampleService {
@CachePut(value = "exampleCache", key = "#param")
public String updateCache(String param) {
return "Updated Data";
}
}
@CacheEvict : This is an annotation commonly used in Spring framework, specifically in the context of caching. It's a meta-annotation that instructs the caching mechanism to remove a specific element from the cache.
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
@Service
public class ExampleService {
@CacheEvict(value = "exampleCache", allEntries = true)
public void clearCache() {
}
}
@CacheConfig is an annotation used to define a set of default cache configurations that can be applied to all methods within a class. This annotation allows you to specify common caching settings, such as the name of the cache to use, the cache manager, and the cache resolver, without having to repeat these settings for each individual method.
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
@CacheConfig(cacheNames = "exampleCache")
public class ExampleService {
@Cacheable
public String getExpensiveData(String param) {
// thực hiện phép toán tốn kém
return "Expensive Data";
}
}
Read more at : Spring Boot's Caching Features