Saltar al contenido principal

Capítulo 2: Caché con Spring Cache y Redis

Objetivos del Capítulo​

  • Comprender los conceptos de almacenamiento en caché
  • Configurar Spring Cache con Redis
  • Utilizar las anotaciones @Cacheable, @CacheEvict, @CachePut
  • Implementar estrategias de caché eficaces
  • Gestionar la expiración e invalidación

1. Introducción al Caching​

1.1 Por qué Usar Caché​

Sin caché:
Cliente → API → Servicio → Base de datos → Servicio → API → Cliente
↓ ↓
10ms 100ms = 110ms total

Con caché:
Cliente → API → Caché → API → Cliente
↓ ↓
10ms 1ms = 11ms total (10x más rápido)

1.2 Tipos de Caché​

TipoDescripciónEjemplo
LocalMemoria de la aplicaciónConcurrentHashMap, Caffeine
DistribuidaServidor externo compartidoRedis, Memcached
CDNContenido estáticoCloudFlare, AWS CloudFront

1.3 Estrategias de Caché​

EstrategiaDescripciónUso
Cache-AsideLa aplicación gestiona la cachéGeneral
Read-ThroughLa caché gestiona las lecturasLecturas frecuentes
Write-ThroughEscribe en caché y BDFuerte coherencia
Write-BehindEscribe en caché, BD asíncronaRendimiento

2. Configuración de Spring Cache con Redis​

2.1 Dependencias 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 conexiones -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
</dependencies>

2.2 Configuración 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 hora en ms
cache-null-values: false
use-key-prefix: true
key-prefix: "myapp:"

2.3 Configuración 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) {
// Configuración por defecto
RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1))
.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new StringRedisSerializer()))
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer()))
.disableCachingNullValues();

// Configuraciones específicas por caché
Map<String, RedisCacheConfiguration> cacheConfigs = new HashMap<>();

// Caché de productos: TTL 30 minutos
cacheConfigs.put("products", defaultConfig.entryTtl(Duration.ofMinutes(30)));

// Caché de usuarios: TTL 1 hora
cacheConfigs.put("users", defaultConfig.entryTtl(Duration.ofHours(1)));

// Caché de búsqueda: TTL 5 minutos
cacheConfigs.put("search", defaultConfig.entryTtl(Duration.ofMinutes(5)));

return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(defaultConfig)
.withInitialCacheConfigurations(cacheConfigs)
.transactionAware()
.build();
}
}

3. Anotaciones de Caché​

3.1 @Cacheable​

Almacena en caché el resultado de un método.

@Service
public class ProductService {

private final ProductRepository productRepository;

public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}

// Caché simple con ID como clave
@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));
}

// Caché con clave compuesta
@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));
}

// Caché condicional
@Cacheable(value = "products", key = "#id", condition = "#id > 0")
public Product getProductConditional(Long id) {
return productRepository.findById(id).orElse(null);
}

// No almacenar en caché si es null
@Cacheable(value = "products", key = "#id", unless = "#result == null")
public Product getProductUnlessNull(Long id) {
return productRepository.findById(id).orElse(null);
}
}

3.2 @CacheEvict​

Elimina entradas de la caché.

@Service
public class ProductService {

// Elimina una entrada específica
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}

// Elimina todas las entradas de la caché
@CacheEvict(value = "products", allEntries = true)
public void clearProductCache() {
log.info("Product cache cleared");
}

// Elimina antes de la ejecución
@CacheEvict(value = "products", key = "#id", beforeInvocation = true)
public void deleteProductBeforeInvocation(Long id) {
productRepository.deleteById(id);
}

// Elimina después de la actualización
@CacheEvict(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
return productRepository.save(product);
}
}

3.3 @CachePut​

Actualiza la caché sin comprobar si existe.

@Service
public class ProductService {

// Actualiza la caché con el nuevo producto
@CachePut(value = "products", key = "#product.id")
public Product createProduct(Product product) {
return productRepository.save(product);
}

// Actualiza la caché después de la modificación
@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 (Combinación)​

@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 (Configuración de Clase)​

@Service
@CacheConfig(cacheNames = "products")
public class ProductService {

@Cacheable(key = "#id") // Usa la caché "products"
public Product getById(Long id) { ... }

@CacheEvict(key = "#id") // Usa la caché "products"
public void delete(Long id) { ... }
}

4. Claves de Caché Personalizadas​

4.1 SpEL para las Claves​

// Parámetro simple
@Cacheable(key = "#id")

// Propiedad de objeto
@Cacheable(key = "#product.id")

// Concatenación
@Cacheable(key = "#category + ':' + #page")

// Método sobre parámetro
@Cacheable(key = "#name.toLowerCase()")

// Resultado (para @CachePut)
@CachePut(key = "#result.id")

// Variables root
@Cacheable(key = "#root.method.name + '_' + #id")
@Cacheable(key = "#root.targetClass.simpleName + '_' + #id")

4.2 KeyGenerator Personalizado​

@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) {
// Clave generada: ProductService.searchProducts_laptop_electronics_1000.0
return productRepository.search(name, category, maxPrice);
}

5. RedisTemplate para Operaciones Avanzadas​

5.1 Configuración​

@Configuration
public class RedisConfig {

@Bean
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);

// Serialización de claves como String
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());

// Serialización de valores como JSON
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

template.afterPropertiesSet();
return template;
}
}

5.2 Operaciones​

@Service
public class RedisCacheService {

private final RedisTemplate<String, Object> redisTemplate;

public RedisCacheService(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}

// Operaciones 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);
}

// Operaciones 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);
}

// Operaciones 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);
}

// Operaciones 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 y eliminación
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. Patrones de Caché​

6.1 Cache-Aside (Carga Perezosa)​

@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. Verificar la caché
Product cached = redisTemplate.opsForValue().get(key);
if (cached != null) {
return cached;
}

// 2. Cache miss: cargar desde BD
Product product = repository.findById(id)
.orElseThrow(() -> new ProductNotFoundException(id));

// 3. Almacenar en caché
redisTemplate.opsForValue().set(key, product, CACHE_TTL);

return product;
}

public void updateProduct(Product product) {
// 1. Actualizar BD
repository.save(product);

// 2. Invalidar la caché
String key = "product:" + product.getId();
redisTemplate.delete(key);
}
}

6.2 Write-Through​

@Service
public class ProductWriteThroughService {

public Product saveProduct(Product product) {
// 1. Guardar en BD
Product saved = repository.save(product);

// 2. Actualizar la caché inmediatamente
String key = "product:" + saved.getId();
redisTemplate.opsForValue().set(key, saved, CACHE_TTL);

return saved;
}
}

6.3 Cache Warming (Precarga)​

@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...");

// Cargar los productos populares al inicio
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. Gestión de Errores​

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());
// No propagar el error - continuar sin caché
}

@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. Monitorización​

8.1 Actuator Endpoints​

management:
endpoints:
web:
exposure:
include: health,caches,metrics
endpoint:
caches:
enabled: true
# Lista de cachés
curl http://localhost:8080/actuator/caches

# Métricas de caché
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étricas Personalizadas​

@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. Resumen​

Anotaciones​

AnotaciónAcción
@CacheableLee de la caché o ejecuta y almacena en caché
@CachePutSiempre ejecuta y actualiza la caché
@CacheEvictElimina de la caché
@CachingCombina varias anotaciones
@CacheConfigConfiguración a nivel de clase

Buenas Prácticas​

  1. Definir TTL apropiados por tipo de dato
  2. Utilizar claves significativas y coherentes
  3. Invalidar la caché en las actualizaciones
  4. Gestionar los errores de Redis de forma elegante
  5. Monitorizar los ratios de hit/miss
  6. No almacenar en caché datos sensibles
  7. Prever la precarga de caché para datos críticos

Capítulo Siguiente: Mensajería con RabbitMQ

Volver al Módulo 14