0Pricing
Spring Boot 4 Microservices & REST APIs · Aula

TTL e invalidação do cache

Gerencie a expiração e a remoção do cache.

TTL e invalidação do cache é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Why TTL Matters

Cached data can go stale. A TTL (time-to-live) automatically expires entries after a set duration, bounding how stale data can get.

Setting a Default TTL

Apply a TTL to all caches via the default configuration.

RedisCacheConfiguration config =
    RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofMinutes(10));

Per-Cache TTL

Different data ages at different rates — give each cache its own TTL.

Map<String, RedisCacheConfiguration> configs = Map.of(
    "products",
        RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofHours(1)),
    "prices",
        RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMinutes(1)));

Caffeine TTL via Properties

For a local Caffeine cache, set expiry in properties.

spring.cache.caffeine.spec=expireAfterWrite=300s,maximumSize=1000

Explicit Invalidation

TTL handles time-based expiry; @CacheEvict handles event-based invalidation when data changes.

@CacheEvict(value = "products", key = "#id")
public void delete(Long id) {
    repository.deleteById(id);
}

Write-Through Updates

Pair an update with @CachePut so the cache reflects the new value immediately instead of waiting for expiry.

@CachePut(value = "products", key = "#product.id")
public Product update(Product product) {
    return repository.save(product);
}

Clearing a Whole Cache

After a bulk change, evict all entries to force fresh reads.

@CacheEvict(value = "products", allEntries = true)
public void importBatch(List<Product> items) {
    repository.saveAll(items);
}

Eviction Policies

When a cache hits its size limit, an eviction policy decides what to remove. Common policies: LRU (least recently used) and LFU (least frequently used).

Bounding Cache Size

Limit memory by capping the number of entries with Caffeine's maximumSize.

spring.cache.caffeine.spec=maximumSize=10000

Cache Stampede

When a popular key expires, many requests miss at once and all hit the database — a stampede. Mitigate with short staggered TTLs or refresh-ahead strategies.

Monitoring Hit Rate

Track the cache hit rate (hits ÷ total lookups). A low rate means the cache is not helping — revisit TTL, keys, or whether caching fits the access pattern.

Quick Check

Test your understanding of TTL and invalidation.

Recap

You learned cache expiry and invalidation:

  • TTL via entryTtl bounds staleness
  • Per-cache TTLs for different data
  • @CacheEvict / @CachePut for event-based invalidation
  • Eviction policies (LRU/LFU), size limits, and stampede awareness

Perguntas Frequentes

A aula “TTL e invalidação do cache” é grátis?

Sim — o texto completo de “TTL e invalidação do cache” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

O que vou aprender em “TTL e invalidação do cache”?

Gerencie a expiração e a remoção do cache. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?

Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “TTL e invalidação do cache”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?

Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. A abstração de cache do Spring
  2. @Cacheable, @CachePut, @CacheEvict
  3. Redis como provedor de cache
  4. TTL e invalidação do cache
← Voltar para Spring Boot 4 Microservices & REST APIs