Sub topic 1
Why and when to cache
Prerequisites
Assume basic Java, Spring Boot, dependency injection, and application.properties or application.yml. A cache is temporary storage for data that an application can reuse. Caching helps when reading data is slower than reading from memory, such as querying a database or calling a remote service.
Caching reduces response time and repeated work. It also introduces trade-offs:
- Cached data can become stale.
- The application needs memory or another storage service.
- Updates must keep the cache consistent.
- A cache miss still performs the original slow operation.
Use caching for frequently read data that does not change every moment. Avoid caching data when stale values could cause serious harm or when nearly every request needs a fresh value.
How Spring's cache abstraction works
Spring's cache abstraction provides common annotations and interfaces without tying application code to one cache provider. A Cache stores entries, and a CacheManager creates and manages named caches.
When a method marked with @Cacheable runs, Spring checks the named cache first. On a hit, it returns the stored result without calling the method. On a miss, it calls the method, stores the result, and returns it.
Enabling caching in a Spring Boot application
Add spring-boot-starter-cache to the project. Then place @EnableCaching on a configuration or application class. This activates Spring's annotation-driven cache support.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}Spring Boot can then configure a provider such as Caffeine or Redis when its dependency and properties are present.
Caching method results with `@Cacheable`
Put @Cacheable on a Spring bean method whose result can be reused. The cache name identifies the cache, and key defines the entry key.
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
class ProductService {
@Cacheable(cacheNames = "products", key = "#id")
public String findById(Long id) {
return "loaded product " + id; // Replace with a database call.
}
}For findById(7L), Spring first checks key 7. The second call can return the cached string without executing the method.
Exercise
Why might caching every method result be a poor design?
Show answer
It can return stale data, consume unnecessary storage, and hide changes that users expect to see immediately.