In Spring Boot, when cached data is updated by the user, you should use cache eviction or update mechanisms like @CacheEvict, @CachePut, or a write-through strategy to ensure consistency between cache and database.
Here’s how to handle this effectively:
๐ 1. Use @CacheEvict to Remove Stale Data
When a user updates data, you can evict the corresponding cache entry so that future reads fetch fresh data from the database.
@CacheEvict(value = "users", key = "#user.id")
public void updateUser(User user) {
userRepository.save(user);
}
value: cache namekey: identifies the specific entry to evict- You can also use
allEntries = trueto clear the entire cache if needed.
๐ 2. Use @CachePut to Update Cache After Write
If you want to update the cache immediately after modifying the data:
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
return userRepository.save(user);
}
- This ensures the cache is updated with the latest data after the DB write.
๐ง 3. Use Cache-Aside Strategy with Manual Invalidation
Let the application manage cache reads and writes explicitly:
public User getUser(Long id) {
return cache.getOrElse(id, () -> userRepository.findById(id));
}
public void updateUser(User user) {
userRepository.save(user);
cache.remove(user.getId()); // or cache.put(user.getId(), user)
}
- This gives you full control over cache lifecycle.
⚙️ 4. Write-Through Strategy with Redis or Caffeine
Use Spring Boot with Redis or Caffeine to automatically write to both cache and DB.
- With Redis, you can configure TTL and use pub/sub for distributed invalidation.
- With Caffeine, you can use
refreshAfterWriteorexpireAfterWritefor auto-refresh.
๐งช 5. Testing and Monitoring
- Use Actuator endpoints to inspect cache state.
- Log cache hits/misses to tune performance.
- Consider using Spring Events or AOP to centralize cache invalidation logic.
Would you like a ready-to-use Spring Boot service layer example with Redis or Caffeine showing @Cacheable, @CacheEvict, and @CachePut in action?
No comments:
Post a Comment