#1
Database queries can slow down applications when the same data is requested repeatedly. Redis can solve this problem by acting as a cache layer between your application and database. With caching, frequently accessed data is stored in memory, making responses much faster.
This guide explains how to implement Redis caching in Spring Boot using simple annotations.

1. Enable Caching in Spring Boot

First, enable caching support in your main application class.
@SpringBootApplication
@EnableCaching
public class RedisCacheApplication {}
The @EnableCaching annotation activates Spring Boot’s caching mechanism.

2. Configure Redis Cache

Add Redis connection settings in application.properties.
spring.redis.host=localhost
spring.redis.port=6379
spring.cache.type=redis
Spring Boot will automatically configure Redis as the cache provider.

3. Caching Data with @Cacheable

The @Cacheable annotation stores the result of a method in Redis.
Example service:
@Service
public class ProductService {
    public String getProductById(Long id) {
        simulateSlowQuery();
        return "Product " + id;
    }
    
    private void simulateSlowQuery() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException ignored) {}
    }
}
Add caching:
@Cacheable(value = "products", key = "#id")
public String getProductById(Long id) {
    simulateSlowQuery();
    return "Product " + id;
}
Now the first request takes 3 seconds, but the next requests return instantly from Redis.

4. Updating Cache with @CachePut

When data changes, the cache should also be updated.
@CachePut(value = "products", key = "#id")
public String updateProduct(Long id, String name) {
    return name;
}
This updates both the database and the cached value.

5. Removing Cache with @CacheEvict

If data is deleted or invalid, remove it from Redis.
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
    System.out.println("Product removed");
}

This ensures the application does not return outdated data.

6. Using Cache in REST API

Expose cached data through a simple controller.
@RestController
@RequestMapping("/products")
public class ProductController {
    @Autowired
    private ProductService productService;
    
    @GetMapping("/{id}")
    public String getProduct(@PathVariable Long id) {
        return productService.getProductById(id);
    }
}
The first request loads from the service, while subsequent requests come from Redis.

7. Setting Cache Expiration

You can define cache TTL (time-to-live) to automatically remove old data.
Example configuration:
@Bean
public RedisCacheConfiguration cacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(class="ͼt">Duration.ofMinutes(10));
}
This means cached data expires after 10 minutes.
#ads

image quote pre code