Chapitre 2: Cache avec Spring Cache et Redis
Objectifs du Chapitre
- Comprendre les concepts de mise en cache
- Configurer Spring Cache avec Redis
- Utiliser les annotations @Cacheable, @CacheEvict, @CachePut
- Implémenter des stratégies de cache efficaces
- Gérer l'expiration et l'invalidation
1. Introduction au Caching
1.1 Pourquoi Mettre en Cache
Sans cache:
Client → API → Service → Database → Service → API → Client
↓ ↓
10ms 100ms = 110ms total
Avec cache:
Client → API → Cache → API → Client
↓ ↓
10ms 1ms = 11ms total (10x plus rapide)
1.2 Types de Cache
| Type | Description | Exemple |
|---|---|---|
| Local | Mémoire de l'application | ConcurrentHashMap, Caffeine |
| Distribué | Serveur externe partagé | Redis, Memcached |
| CDN | Contenu statique | CloudFlare, AWS CloudFront |
1.3 Stratégies de Cache
| Stratégie | Description | Usage |
|---|---|---|
| Cache-Aside | App gère le cache | Général |
| Read-Through | Cache gère les lectures | Lectures fréquentes |
| Write-Through | Écrit dans cache et DB | Cohérence forte |
| Write-Behind | Écrit cache, DB async | Performance |
2. Configuration Spring Cache avec Redis
2.1 Dépendances Maven
<dependencies>
<!-- Spring Cache -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Pool de connexions -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
</dependencies>
2.2 Configuration application.yml
spring:
data:
redis:
host: localhost
port: 6379
password: ""
timeout: 2000ms
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 2
max-wait: -1ms
cache:
type: redis
redis:
time-to-live: 3600000 # 1 heure en ms
cache-null-values: false
use-key-prefix: true
key-prefix: "myapp:"
2.3 Configuration Java
package com.example.cache.config;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
// Configuration par défaut
RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1))
.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new StringRedisSerializer()))
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer()))
.disableCachingNullValues();
// Configurations spécifiques par cache
Map<String, RedisCacheConfiguration> cacheConfigs = new HashMap<>();
// Cache produits: TTL 30 minutes
cacheConfigs.put("products", defaultConfig.entryTtl(Duration.ofMinutes(30)));
// Cache utilisateurs: TTL 1 heure
cacheConfigs.put("users", defaultConfig.entryTtl(Duration.ofHours(1)));
// Cache recherche: TTL 5 minutes
cacheConfigs.put("search", defaultConfig.entryTtl(Duration.ofMinutes(5)));
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(defaultConfig)
.withInitialCacheConfigurations(cacheConfigs)
.transactionAware()
.build();
}
}
3. Annotations de Cache
3.1 @Cacheable
Met en cache le résultat d'une méthode.
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
// Cache simple avec ID comme clé
@Cacheable(value = "products", key = "#id")
public Product getProductById(Long id) {
log.info("Fetching product {} from database", id);
return productRepository.findById(id)
.orElseThrow(() -> new ProductNotFoundException(id));
}
// Cache avec clé composée
@Cacheable(value = "products", key = "#category + '_' + #page")
public List<Product> getProductsByCategory(String category, int page) {
log.info("Fetching products for category {} page {}", category, page);
return productRepository.findByCategory(category, PageRequest.of(page, 20));
}
// Cache conditionnel
@Cacheable(value = "products", key = "#id", condition = "#id > 0")
public Product getProductConditional(Long id) {
return productRepository.findById(id).orElse(null);
}
// Ne pas cacher si null
@Cacheable(value = "products", key = "#id", unless = "#result == null")
public Product getProductUnlessNull(Long id) {
return productRepository.findById(id).orElse(null);
}
}
3.2 @CacheEvict
Supprime des entrées du cache.
@Service
public class ProductService {
// Supprime une entrée spécifique
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
// Supprime toutes les entrées du cache
@CacheEvict(value = "products", allEntries = true)
public void clearProductCache() {
log.info("Product cache cleared");
}
// Supprime avant l'exécution
@CacheEvict(value = "products", key = "#id", beforeInvocation = true)
public void deleteProductBeforeInvocation(Long id) {
productRepository.deleteById(id);
}
// Supprime après mise à jour
@CacheEvict(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
return productRepository.save(product);
}
}
3.3 @CachePut
Met à jour le cache sans vérifier s'il existe.
@Service
public class ProductService {
// Met à jour le cache avec le nouveau produit
@CachePut(value = "products", key = "#product.id")
public Product createProduct(Product product) {
return productRepository.save(product);
}
// Met à jour le cache après modification
@CachePut(value = "products", key = "#result.id")
public Product updateProduct(Long id, ProductRequest request) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new ProductNotFoundException(id));
product.setName(request.getName());
product.setPrice(request.getPrice());
return productRepository.save(product);
}
}
3.4 @Caching (Combinaison)
@Service
public class ProductService {
@Caching(
put = { @CachePut(value = "products", key = "#result.id") },
evict = {
@CacheEvict(value = "productList", allEntries = true),
@CacheEvict(value = "search", allEntries = true)
}
)
public Product saveProduct(Product product) {
return productRepository.save(product);
}
}
3.5 @CacheConfig (Configuration Classe)
@Service
@CacheConfig(cacheNames = "products")
public class ProductService {
@Cacheable(key = "#id") // Utilise le cache "products"
public Product getById(Long id) { ... }
@CacheEvict(key = "#id") // Utilise le cache "products"
public void delete(Long id) { ... }
}
4. Clés de Cache Personnalisées
4.1 SpEL pour les Clés
// Paramètre simple
@Cacheable(key = "#id")
// Propriété d'objet
@Cacheable(key = "#product.id")
// Concaténation
@Cacheable(key = "#category + ':' + #page")
// Méthode sur paramètre
@Cacheable(key = "#name.toLowerCase()")
// Résultat (pour @CachePut)
@CachePut(key = "#result.id")
// Variables root
@Cacheable(key = "#root.method.name + '_' + #id")
@Cacheable(key = "#root.targetClass.simpleName + '_' + #id")
4.2 KeyGenerator Personnalisé
@Configuration
public class CacheConfig {
@Bean
public KeyGenerator customKeyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getSimpleName());
sb.append(".");
sb.append(method.getName());
for (Object param : params) {
sb.append("_");
sb.append(param != null ? param.toString() : "null");
}
return sb.toString();
};
}
}
@Cacheable(value = "products", keyGenerator = "customKeyGenerator")
public List<Product> searchProducts(String name, String category, Double maxPrice) {
// Clé générée: ProductService.searchProducts_laptop_electronics_1000.0
return productRepository.search(name, category, maxPrice);
}
5. RedisTemplate pour Opérations Avancées
5.1 Configuration
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
// Sérialisation des clés en String
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
// Sérialisation des valeurs en JSON
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
5.2 Opérations
@Service
public class RedisCacheService {
private final RedisTemplate<String, Object> redisTemplate;
public RedisCacheService(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
// Opérations String
public void setValue(String key, Object value, Duration ttl) {
redisTemplate.opsForValue().set(key, value, ttl);
}
public Object getValue(String key) {
return redisTemplate.opsForValue().get(key);
}
public Boolean setIfAbsent(String key, Object value, Duration ttl) {
return redisTemplate.opsForValue().setIfAbsent(key, value, ttl);
}
// Opérations Hash
public void setHashField(String key, String field, Object value) {
redisTemplate.opsForHash().put(key, field, value);
}
public Object getHashField(String key, String field) {
return redisTemplate.opsForHash().get(key, field);
}
public Map<Object, Object> getHash(String key) {
return redisTemplate.opsForHash().entries(key);
}
// Opérations List
public void addToList(String key, Object value) {
redisTemplate.opsForList().rightPush(key, value);
}
public List<Object> getList(String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
}
// Opérations Set
public void addToSet(String key, Object... values) {
redisTemplate.opsForSet().add(key, values);
}
public Set<Object> getSet(String key) {
return redisTemplate.opsForSet().members(key);
}
// TTL et suppression
public Boolean expire(String key, Duration ttl) {
return redisTemplate.expire(key, ttl);
}
public Boolean delete(String key) {
return redisTemplate.delete(key);
}
public Long deleteByPattern(String pattern) {
Set<String> keys = redisTemplate.keys(pattern);
if (keys != null && !keys.isEmpty()) {
return redisTemplate.delete(keys);
}
return 0L;
}
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
}
6. Patterns de Cache
6.1 Cache-Aside (Lazy Loading)
@Service
public class ProductCacheService {
private final ProductRepository repository;
private final RedisTemplate<String, Product> redisTemplate;
private static final Duration CACHE_TTL = Duration.ofMinutes(30);
public Product getProduct(Long id) {
String key = "product:" + id;
// 1. Vérifier le cache
Product cached = redisTemplate.opsForValue().get(key);
if (cached != null) {
return cached;
}
// 2. Cache miss: charger depuis DB
Product product = repository.findById(id)
.orElseThrow(() -> new ProductNotFoundException(id));
// 3. Mettre en cache
redisTemplate.opsForValue().set(key, product, CACHE_TTL);
return product;
}
public void updateProduct(Product product) {
// 1. Mettre à jour DB
repository.save(product);
// 2. Invalider le cache
String key = "product:" + product.getId();
redisTemplate.delete(key);
}
}
6.2 Write-Through
@Service
public class ProductWriteThroughService {
public Product saveProduct(Product product) {
// 1. Sauvegarder en DB
Product saved = repository.save(product);
// 2. Mettre à jour le cache immédiatement
String key = "product:" + saved.getId();
redisTemplate.opsForValue().set(key, saved, CACHE_TTL);
return saved;
}
}
6.3 Cache Warming (Préchauffage)
@Component
public class CacheWarmer implements ApplicationRunner {
private final ProductRepository productRepository;
private final RedisTemplate<String, Product> redisTemplate;
@Override
public void run(ApplicationArguments args) {
log.info("Warming up product cache...");
// Charger les produits populaires au démarrage
List<Product> popularProducts = productRepository.findTop100ByOrderBySalesDesc();
popularProducts.forEach(product -> {
String key = "product:" + product.getId();
redisTemplate.opsForValue().set(key, product, Duration.ofHours(24));
});
log.info("Cache warmed with {} products", popularProducts.size());
}
}
7. Gestion des Erreurs
7.1 CacheErrorHandler
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
@Override
public CacheErrorHandler errorHandler() {
return new SimpleCacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException ex, Cache cache, Object key) {
log.warn("Cache get error for key {} in cache {}: {}",
key, cache.getName(), ex.getMessage());
// Ne pas propager l'erreur - continuer sans cache
}
@Override
public void handleCachePutError(RuntimeException ex, Cache cache,
Object key, Object value) {
log.warn("Cache put error for key {} in cache {}: {}",
key, cache.getName(), ex.getMessage());
}
@Override
public void handleCacheEvictError(RuntimeException ex, Cache cache, Object key) {
log.warn("Cache evict error for key {} in cache {}: {}",
key, cache.getName(), ex.getMessage());
}
@Override
public void handleCacheClearError(RuntimeException ex, Cache cache) {
log.warn("Cache clear error for cache {}: {}",
cache.getName(), ex.getMessage());
}
};
}
}
8. Monitoring
8.1 Actuator Endpoints
management:
endpoints:
web:
exposure:
include: health,caches,metrics
endpoint:
caches:
enabled: true
# Liste des caches
curl http://localhost:8080/actuator/caches
# Métriques cache
curl http://localhost:8080/actuator/metrics/cache.gets
curl http://localhost:8080/actuator/metrics/cache.puts
curl http://localhost:8080/actuator/metrics/cache.evictions
8.2 Métriques Custom
@Service
public class ProductService {
private final MeterRegistry meterRegistry;
private final Counter cacheHits;
private final Counter cacheMisses;
public ProductService(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
this.cacheHits = meterRegistry.counter("product.cache.hits");
this.cacheMisses = meterRegistry.counter("product.cache.misses");
}
public Product getProduct(Long id) {
Product cached = getFromCache(id);
if (cached != null) {
cacheHits.increment();
return cached;
}
cacheMisses.increment();
return loadFromDatabase(id);
}
}
9. Résumé
Annotations
| Annotation | Action |
|---|---|
@Cacheable | Lit du cache ou exécute et cache |
@CachePut | Exécute toujours et met à jour le cache |
@CacheEvict | Supprime du cache |
@Caching | Combine plusieurs annotations |
@CacheConfig | Configuration au niveau classe |
Bonnes Pratiques
- Définir des TTL appropriés par type de données
- Utiliser des clés significatives et cohérentes
- Invalider le cache lors des mises à jour
- Gérer les erreurs Redis gracieusement
- Monitorer les hit/miss ratios
- Ne pas cacher les données sensibles
- Prévoir le cache warming pour les données critiques