Caching reduces database load and delivers sub-millisecond API responses. Learn how to implement Cache-Aside, handle Cache Stampede (Thundering Herd) with distributed locks, and configure Redis Cluster Sentinel failover.
1. Cache-Aside Pattern Implementation
public UserDto getUserById(Long userId) {
String cacheKey = "user:" + userId;
// 1. Try Redis Cache Hit
UserDto cachedUser = redisTemplate.opsForValue().get(cacheKey);
if (cachedUser != null) {
return cachedUser; // Sub-2ms response
}
// 2. Cache Miss: Query Database (150ms)
UserDto dbUser = userRepository.findById(userId)
.map(this::convertToDto)
.orElseThrow(() -> new ResourceNotFoundException("User not found"));
// 3. Populate Redis Cache with 1-hour TTL
redisTemplate.opsForValue().set(cacheKey, dbUser, Duration.ofHours(1));
return dbUser;
}