Spring Data Redis:Repository与CachingConfigurer实现错误处理及save错误捕获问询
@Repository (Spring Data Redis) Work with CachingConfigurer for Error Handling? Great question! Let's break down exactly what's happening here and clarify whether your custom RedisCacheError will catch errors from CrudRepository.save().
Key: Spring Cache Abstraction vs. Spring Data Redis Repository Operations
First, it's critical to distinguish between two separate Spring features here:
- Spring Cache Abstraction: This is what your
CachingConfigurerandCacheErrorHandlerare tied to. It handles operations triggered by cache annotations like@Cacheable,@CachePut,@CacheEvict—these are meant for caching data to improve performance, not for primary data storage. - Spring Data Redis Repositories: Your
ObjectRepositoryextendingCrudRepositoryis part of Spring Data's data access layer. It uses Redis as a database (not just a cache), so operations likesave(),findById(), etc., directly interact with Redis to persist/fetch data.
Does CrudRepository.save() Use redis.add()?
When using Spring Data Redis's CrudRepository, the save() method doesn't call a cache-specific add() or put() from the Spring Cache abstraction. Instead, it uses RedisTemplate under the hood to perform Redis data operations:
- For new entities, it typically uses
opsForValue().set()(or similar for hash/set structures) to store the data directly in Redis. - For updates, it overwrites the existing key-value pair.
This is a data persistence operation, not a caching operation.
Will Your RedisCacheError Catch save() Errors?
Short answer: No.
Your RedisCacheError implements CacheErrorHandler, which is designed exclusively to handle errors that occur during Spring Cache abstraction operations (like when @CachePut tries to write to a cache, or @Cacheable tries to read from one). It has no visibility into errors from Spring Data Redis Repository operations, because those aren't part of the cache abstraction workflow.
If Redis goes down or throws an error during save(), the exception will bubble up as a standard Spring Data access exception (like RedisConnectionFailureException)—your CacheErrorHandler methods won't trigger at all.
How to Catch Errors from CrudRepository Operations
To handle errors from your repository's data access operations, you have a few options:
Global Exception Handler
Use Spring's@ControllerAdviceto catch Redis-specific exceptions across your application:import org.springframework.data.redis.RedisConnectionFailureException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ControllerAdvice public class RedisDataAccessErrorHandler { private static final Logger log = LoggerFactory.getLogger(RedisDataAccessErrorHandler.class); @ExceptionHandler(RedisConnectionFailureException.class) public ResponseEntity<String> handleRedisConnectionFailure(RedisConnectionFailureException ex) { log.info("Caught Redis error during repository operation: {}", ex.getMessage()); // Add custom logic here (e.g., fallback, alerting) return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("Failed to connect to Redis"); } // Add other exception handlers for Redis-specific errors as needed }Custom RedisTemplate with Error Handling
If you want more granular control at the Redis interaction level, you can customize yourRedisTemplateto handle errors during operations. For example, wrap Redis operations in a try-catch block usingRedisCallback:@Autowired private RedisTemplate<String, Object> redisTemplate; public <T> T executeWithErrorHandling(RedisCallback<T> callback) { try { return redisTemplate.execute(callback); } catch (RedisConnectionFailureException ex) { log.info("Redis operation failed: {}", ex.getMessage()); // Add fallback logic return null; // Or throw a custom exception } }You could then use this wrapper in a custom repository implementation instead of relying on the default
CrudRepositoryproxy.
Summary
- Use
CacheErrorHandlerfor Spring Cache annotation operations (@Cacheable,@CachePut, etc.) - Use global exception handlers or custom
RedisTemplatewrappers for Spring Data Redis Repository operations (save(),find(), etc.)
内容的提问来源于stack exchange,提问作者aspiringCoder

