Tired of slow API responses hitting your database for the same data repeatedly? It's a common bottleneck. Instead of always fetching from the primary store, let's put Redis to work for blazing fast reads.
Spring Boot makes this incredibly simple. Just enable caching with @EnableCaching on your configuration class and then mark methods that produce frequently accessed but slow-to-retrieve data with @Cacheable.
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
@Cacheable(value = "products", key = "#id")
public Product getProductById(Long id) {
System.out.println("Fetching product from DB: " + id); // Simulates DB call
return productRepository.findById(id)
.orElseThrow(() -> new NotFoundException("Product not found"));
}
}
The first call for a given id goes to the database and stores the result in Redis under the products cache. Subsequent calls for that same id hit the cache directly, bypassing the database entirely. Remember to configure your CacheManager for Redis. This dramatically cuts down latency for read-heavy operations, giving your users a snappier experience without complex code.
Top comments (0)