javaintermediate
Spring Boot Caching with Redis
Add caching to Spring Boot services with @Cacheable, @CacheEvict, TTL configuration, and Redis.
javaPress ⌘/Ctrl + Shift + C to copy
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.context.annotation.*;
import java.time.Duration;
import java.util.Optional;
@Service
public class ProductService {
private final ProductRepository repository;
public ProductService(ProductRepository repository) {
this.repository = repository;
}
// Cache result — key = method arg
@Cacheable(value = "products", key = "#id")
public Product findById(Long id) {
System.out.println("DB query for: " + id);
return repository.findById(id)
.orElseThrow(() -> new RuntimeException("Not found"));
}
// Cache with condition
@Cacheable(value = "products", key = "#slug", unless = "#result == null")
public Optional<Product> findBySlug(String slug) {
return repository.findBySlug(slug);
}
// Update cache on save
@CachePut(value = "products", key = "#product.id")
public Product save(Product product) {
return repository.save(product);
}
// Evict specific cache entry
@CacheEvict(value = "products", key = "#id")
public void delete(Long id) {
repository.deleteById(id);
}
// Evict all entries in cache
@CacheEvict(value = "products", allEntries = true)
public void clearCache() {
System.out.println("Cache cleared");
}
}
// Redis config
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(30))
.disableCachingNullValues()
.prefixCacheNameWith("app:");
}
}Use Cases
- Reducing database load with application-level caching
- Redis-backed caching for Spring Boot services
- Cache invalidation strategies for CRUD operations
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
Redis Cache-Aside Pattern in Python
Implement cache-aside (lazy loading) with Redis and Python to accelerate repeated database queries.
Best for: query caching
#redis#caching
typescriptadvanced
Redis Cache Get/Set Helper
Type-safe Redis cache wrapper with automatic JSON serialization, TTL support, and cache-aside pattern.
Best for: Database query caching
#redis#cache
typescriptintermediate
In-Memory Caching with LRU Strategy
Implement LRU cache with TTL expiration, size limits, and cache-aside pattern for Node.js applications.
Best for: API response caching
#nodejs#caching
typescriptintermediate
ETag Caching Middleware
Express middleware that generates ETags and handles 304 Not Modified responses for bandwidth savings.
Best for: API caching
#express#caching