- Replies:
- 0
- Words:
- 5684

@SpringBootApplication
@EnableCaching
public class RedisCacheApplication {}
The @EnableCaching annotation activates Spring Boot’s caching mechanism.
application.properties.
spring.redis.host=localhost
spring.redis.port=6379
spring.cache.type=redis
Spring Boot will automatically configure Redis as the cache provider.
@Cacheable annotation stores the result of a method in Redis.@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.
@CachePut(value = "products", key = "#id")
public String updateProduct(Long id, String name) {
return name;
}
This updates both the database and the cached value.
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
System.out.println("Product removed");
}
This ensures the application does not return outdated data.
@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.
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(class="ͼt">Duration.ofMinutes(10));
}
This means cached data expires after 10 minutes.
image quote pre code