Spring Boot Cache
Spring Boot Cache provides a declarative caching abstraction that simplifies adding caching to your application. It supports multiple cache providers including Redis, Caffeine, EhCache, and Hazelcast, allowing you to improve application performance by caching frequently accessed data.
Key Features
Use annotations like @Cacheable, @CacheEvict, and @CachePut to add caching without boilerplate code.
Support for various cache providers including Redis, Caffeine, EhCache, Hazelcast, and simple in-memory cache.
Switch between cache providers without changing application code.
Cache entries conditionally based on method parameters or results.
Use Cases
- Database Query Caching: Caching expensive database queries to reduce load
- API Response Caching: Caching external API responses to improve response times
- Computation Caching: Caching expensive computations and calculations
- Session Caching: Storing session data in distributed cache systems
- Performance Optimization: Improving application performance by reducing redundant operations
Example Usage
Enable caching and use annotations:
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Service
public class UserService {
@Cacheable(value = "users", key = "#id")
public User getUser(Long id) {
return userRepository.findById(id);
}
@CacheEvict(value = "users", key = "#user.id")
public void updateUser(User user) {
userRepository.save(user);
}
@CachePut(value = "users", key = "#user.id")
public User saveUser(User user) {
return userRepository.save(user);
}
}
Dependencies
Add cache starter and provider (e.g., Redis):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Configuration
Configure Redis cache in application.properties:
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
spring.cache.redis.time-to-live=600000