0 day streak
java / beginner
Snippet

Accelerating Expensive Queries Using Cacheable

The @Cacheable annotation stores method return values in a configured cache (e.g., Redis, Caffeine). On subsequent invocations with the same argument key, Spring skips method execution and retrieves the cached result directly.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public Product findProductById(Long id) {
simulateSlowDatabaseCall();
return new Product(id, "Wireless Mouse");
}
private void simulateSlowDatabaseCall() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
spring
Breakdown
1
@Cacheable(value = "products", key = "#id")
Caches the returned Product in the 'products' cache using the 'id' parameter as the cache key.
2
public Product findProductById(Long id) {
Defines the service method that will be bypassed if a cached entry exists for the requested ID.
3
Thread.currentThread().interrupt();
Restores the interrupted status of the current thread when an InterruptedException occurs.