A abstração de cache do Spring
Armazene resultados de métodos em cache com anotações.
A abstração de cache do Spring é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 1 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 Caching
Caching stores the result of expensive operations so repeated calls return instantly from memory instead of recomputing or re-querying.
- Lower latency
- Less database load
- Better throughput
The Cache Abstraction
Spring provides a cache abstraction — a uniform API over many backends (in-memory, Redis, Caffeine). You annotate methods; Spring handles the storage.
Enabling Caching
Add @EnableCaching to a configuration class to turn on annotation processing.
@Configuration
@EnableCaching
public class CacheConfig {
}The CacheManager
A CacheManager owns the named caches. Spring Boot auto-configures one based on what is on the classpath.
@Autowired
CacheManager cacheManager;
Cache productCache = cacheManager.getCache("products");Default In-Memory Cache
With no cache library on the classpath, Spring Boot uses a simple ConcurrentMapCacheManager backed by a map.
Named Caches
Each cached method targets a named cache. Names let you tune and clear caches independently.
@Cacheable("products")
public Product findById(Long id) {
return repository.findById(id).orElseThrow();
}How a Cache Hit Works
On call, Spring builds a key, checks the cache: if present (a hit), it returns the stored value and skips the method body. On a miss, it runs the method and stores the result.
Cache Keys
By default the key is derived from the method arguments. You can override it with a SpEL expression.
@Cacheable(value = "products", key = "#id")
public Product findById(Long id) { ... }Choosing a Provider
Add a library to switch backends automatically: Caffeine for fast local caching, Redis for a shared distributed cache.
// build.gradle for Caffeine
implementation "com.github.ben-manes.caffeine:caffeine"Configuring Caffeine
Caffeine supports size limits and expiry via properties.
# application.properties
spring.cache.cache-names=products
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=600sWhen Not to Cache
Caching suits read-heavy, slow-changing data. Avoid it for rapidly changing values or when stale reads are unacceptable without proper eviction.
Quick Check
Test your understanding of the cache abstraction.
Recap
You learned the cache abstraction:
@EnableCachingturns the feature on- A
CacheManagerowns named caches - Default backend is an in-memory ConcurrentMap
- Swap to Caffeine or Redis by adding the library
Perguntas Frequentes
A aula “A abstração de cache do Spring” é grátis?
Sim — o texto completo de “A abstração de cache do Spring” é 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 “A abstração de cache do Spring”?
Armazene resultados de métodos em cache com anotações. 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 1 de 4.
Quanto tempo leva a aula “A abstração de cache do Spring”?
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
- A abstração de cache do Spring
- @Cacheable, @CachePut, @CacheEvict
- Redis como provedor de cache
- TTL e invalidação do cache