Spring Cache cache kết quả method — swap backend (in-memory, Redis, Caffeine) không đổi code.
java
@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 = "#p.id")
public Product update(Product p) { return repo.save(p); }
@CacheEvict(value = "products", allEntries = true)
public void invalidateAll() {}
}Backend Redis: spring.cache.type: redis. TTL đặt qua RedisCacheManagerBuilderCustomizer (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.