javaintermediate

Spring Boot Caching with Redis

Add caching to Spring Boot services with @Cacheable, @CacheEvict, TTL configuration, and Redis.

java
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.