Spring Cache abstraction cache kết quả method — swap backend (in-memory, Redis, Caffeine) không đổi code.
@SpringBootApplication
@EnableCaching
class App {}
@Service
class ProductService {
@Cacheable(value = "products", key = "#id")
public Product findById(Long id) {
return repo.findById(id).orElseThrow(); // chỉ gọi khi cache miss
}
@CacheEvict(value = "products", key = "#product.id")
public Product update(Product product) {
return repo.save(product);
}
@CacheEvict(value = "products", allEntries = true)
public void invalidateAll() {}
}Redis backend:
spring:
cache.type: redis
data.redis.host: localhostTTL (Redis):
@Bean
RedisCacheManagerBuilderCustomizer customizer() {
return b -> b.withCacheConfiguration("products",
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)));
}Lưu ý: @Cacheable trên @Transactional method — nếu transaction rollback, cache vẫn giữ kết quả cũ (stale).
Dùng @TransactionalEventListener(phase = AFTER_COMMIT) để populate cache chỉ sau khi commit thành công.
Spring Cache abstraction caches method results — swap the backend (in-memory, Redis, Caffeine) without changing code.
@SpringBootApplication
@EnableCaching
class App {}
@Service
class ProductService {
@Cacheable(value = "products", key = "#id")
public Product findById(Long id) {
return repo.findById(id).orElseThrow(); // only called on cache miss
}
@CacheEvict(value = "products", key = "#product.id")
public Product update(Product product) {
return repo.save(product);
}
@CacheEvict(value = "products", allEntries = true)
public void invalidateAll() {}
}Redis backend:
spring:
cache.type: redis
data.redis.host: localhostTTL (Redis):
@Bean
RedisCacheManagerBuilderCustomizer customizer() {
return b -> b.withCacheConfiguration("products",
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)));
}Caveat: @Cacheable on a @Transactional method — if the transaction rolls back, the cache keeps the stale result.
Use @TransactionalEventListener(phase = AFTER_COMMIT) to populate the cache only after a successful commit.