Capítulo 2: Cache com Spring Cache e Redis
Objetivos do Capítulo
- Compreender os conceitos de cache
- Configurar Spring Cache com Redis
- Utilizar as anotações @Cacheable, @CacheEvict, @CachePut
- Implementar estratégias de cache eficientes
- Gerenciar expiração e invalidação
1. Introdução ao Caching
1.1 Por que Usar Cache
Sem cache:
Cliente → API → Service → Database → Service → API → Cliente
↓ ↓
10ms 100ms = 110ms total
Com cache:
Cliente → API → Cache → API → Cliente
↓ ↓
10ms 1ms = 11ms total (10x mais rápido)
1.2 Tipos de Cache
| Tipo | Descrição | Exemplo |
|---|---|---|
| Local | Memória da aplicação | ConcurrentHashMap, Caffeine |
| Distribuído | Servidor externo compartilhado | Redis, Memcached |
| CDN | Conteúdo estático | CloudFlare, AWS CloudFront |
1.3 Estratégias de Cache
| Estratégia | Descrição | Uso |
|---|---|---|
| Cache-Aside | App gerencia o cache | Geral |
| Read-Through | Cache gerencia as leituras | Leituras frequentes |
| Write-Through | Escreve no cache e no DB | Forte consistência |
| Write-Behind | Escreve no cache, DB assíncrono | Performance |
2. Configuração do Spring Cache com Redis
2.1 Dependências 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 conexões -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
</dependencies>
2.2 Configuração 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 em ms
cache-null-values: false
use-key-prefix: true
key-prefix: "myapp:"
2.3 Configuração 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) {
// Configuração padrão
RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1))
.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new StringRedisSerializer()))
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer()))
.disableCachingNullValues();
// Configurações específicas por cache
Map<String, RedisCacheConfiguration> cacheConfigs = new HashMap<>();
// Cache de produtos: TTL 30 minutos
cacheConfigs.put("products", defaultConfig.entryTtl(Duration.ofMinutes(30)));
// Cache de usuários: TTL 1 hora
cacheConfigs.put("users", defaultConfig.entryTtl(Duration.ofHours(1)));
// Cache de busca: TTL 5 minutos
cacheConfigs.put("search", defaultConfig.entryTtl(Duration.ofMinutes(5)));
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(defaultConfig)
.withInitialCacheConfigurations(cacheConfigs)
.transactionAware()
.build();
}
}
3. Anotações de Cache
3.1 @Cacheable
Armazena em cache o resultado de um método.
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
// Cache simples com ID como chave
@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 com chave composta
@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 condicional
@Cacheable(value = "products", key = "#id", condition = "#id > 0")
public Product getProductConditional(Long id) {
return productRepository.findById(id).orElse(null);
}
// Não cachear se for null
@Cacheable(value = "products", key = "#id", unless = "#result == null")
public Product getProductUnlessNull(Long id) {
return productRepository.findById(id).orElse(null);
}
}
3.2 @CacheEvict
Remove entradas do cache.
@Service
public class ProductService {
// Remove uma entrada específica
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
// Remove todas as entradas do cache
@CacheEvict(value = "products", allEntries = true)
public void clearProductCache() {
log.info("Product cache cleared");
}
// Remove antes da execução
@CacheEvict(value = "products", key = "#id", beforeInvocation = true)
public void deleteProductBeforeInvocation(Long id) {
productRepository.deleteById(id);
}
// Remove após atualização
@CacheEvict(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
return productRepository.save(product);
}
}
3.3 @CachePut
Atualiza o cache sem verificar se já existe.
@Service
public class ProductService {
// Atualiza o cache com o novo produto
@CachePut(value = "products", key = "#product.id")
public Product createProduct(Product product) {
return productRepository.save(product);
}
// Atualiza o cache após modificação
@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 (Combinação)
@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 (Configuração de Classe)
@Service
@CacheConfig(cacheNames = "products")
public class ProductService {
@Cacheable(key = "#id") // Usa o cache "products"
public Product getById(Long id) { ... }
@CacheEvict(key = "#id") // Usa o cache "products"
public void delete(Long id) { ... }
}
4. Chaves de Cache Personalizadas
4.1 SpEL para Chaves
// Parâmetro simples
@Cacheable(key = "#id")
// Propriedade de objeto
@Cacheable(key = "#product.id")
// Concatenação
@Cacheable(key = "#category + ':' + #page")
// Método em parâmetro
@Cacheable(key = "#name.toLowerCase()")
// Resultado (para @CachePut)
@CachePut(key = "#result.id")
// Variáveis 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) {
// Chave gerada: ProductService.searchProducts_laptop_electronics_1000.0
return productRepository.search(name, category, maxPrice);
}
5. RedisTemplate para Operações Avançadas
5.1 Configuração
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
// Serialização das chaves em String
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
// Serialização dos valores em JSON
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
5.2 Operações
@Service
public class RedisCacheService {
private final RedisTemplate<String, Object> redisTemplate;
public RedisCacheService(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
// Operações 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);
}
// Operações 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);
}
// Operações 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);
}
// Operações 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 e remoção
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. Padrões 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. Verificar o cache
Product cached = redisTemplate.opsForValue().get(key);
if (cached != null) {
return cached;
}
// 2. Cache miss: carregar do DB
Product product = repository.findById(id)
.orElseThrow(() -> new ProductNotFoundException(id));
// 3. Armazenar em cache
redisTemplate.opsForValue().set(key, product, CACHE_TTL);
return product;
}
public void updateProduct(Product product) {
// 1. Atualizar DB
repository.save(product);
// 2. Invalidar o cache
String key = "product:" + product.getId();
redisTemplate.delete(key);
}
}
6.2 Write-Through
@Service
public class ProductWriteThroughService {
public Product saveProduct(Product product) {
// 1. Salvar no DB
Product saved = repository.save(product);
// 2. Atualizar o cache imediatamente
String key = "product:" + saved.getId();
redisTemplate.opsForValue().set(key, saved, CACHE_TTL);
return saved;
}
}
6.3 Cache Warming (Pré-aquecimento)
@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...");
// Carregar produtos populares na inicialização
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. Tratamento de Erros
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());
// Não propagar o erro - continuar sem 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. Monitoramento
8.1 Actuator Endpoints
management:
endpoints:
web:
exposure:
include: health,caches,metrics
endpoint:
caches:
enabled: true
# Lista de caches
curl http://localhost:8080/actuator/caches
# Métricas de 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étricas Customizadas
@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. Resumo
Anotações
| Anotação | Ação |
|---|---|
@Cacheable | Lê do cache ou executa e armazena no cache |
@CachePut | Sempre executa e atualiza o cache |
@CacheEvict | Remove do cache |
@Caching | Combina múltiplas anotações |
@CacheConfig | Configuração a nível de classe |
Boas Práticas
- Definir TTLs apropriados por tipo de dado
- Utilizar chaves significativas e consistentes
- Invalidar o cache em atualizações
- Tratar erros do Redis de forma graciosa
- Monitorar as taxas de hit/miss
- Não armazenar dados sensíveis em cache
- Planejar cache warming para dados críticos