Caching Implementation with Spring Cache in Microservices
1. Configuration Setup
Import the required dependency in your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
Configure cache settings in application.yml:
spring:
cache:
type: redis
cache-names: productCache
Add the @EnableCaching annotation to your main application class to activate caching functionality.
2. Core Cache Annotations
2.1 @Cacheable
Place @Cacheable above service layer implementation methods:
@Cacheable(value = {"inventoryCache", "stockCache"}, key = "'productId:' + #id")
public Product getProductById(Long id) {
return productRepository.findById(id);
}
This annotation stores method results in cache. When subsequent calls occur with the same parameters, the cached result is returned immediately without executing the method body. If no cached entry exists, the method executes normally and the result gets stored for future requests.
The value parameter defines cache namespace(s). When key is omitted, the cache name serves as the key prefix.
2.2 @CacheEvict
Understanding cache synchronization strategies is essential before implementing eviction:
Invalidation Pattern: Write data to the database, then remove the corresponding cache entry. When the next request arrives, the cache rebuilds dynamically.
Write-Through Pattern: Write data to the database, then immediately write the modified value to cache.
Apply @CacheEvict to methods that modify cached data:
@CacheEvict(value = "inventoryCache", key = "'productId:' + #product.id")
public void updateProduct(Product product) {
productRepository.save(product);
}
When this method executes, the specified cache entry is automatically removed, implementing the invalidasion pattern.
For removing all antries within a cache namespace, use allEntries = true:
@CacheEvict(value = "inventoryCache", allEntries = true)
public void clearInventoryCache() {
// operations that require full cache invalidation
}
Note: Unlike @Cacheable, @CacheEvict does not support multiple cache names in the value parameter.
The @CachePut annotation corresponds to the write-through pattern, updating cache entries after database modifications without affecting method return values.