You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Data Redis:Repository与CachingConfigurer实现错误处理及save错误捕获问询

Can @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 CachingConfigurer and CacheErrorHandler are 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 ObjectRepository extending CrudRepository is part of Spring Data's data access layer. It uses Redis as a database (not just a cache), so operations like save(), 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:

  1. Global Exception Handler
    Use Spring's @ControllerAdvice to 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
    }
    
  2. Custom RedisTemplate with Error Handling
    If you want more granular control at the Redis interaction level, you can customize your RedisTemplate to handle errors during operations. For example, wrap Redis operations in a try-catch block using RedisCallback:

    @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 CrudRepository proxy.

Summary

  • Use CacheErrorHandler for Spring Cache annotation operations (@Cacheable, @CachePut, etc.)
  • Use global exception handlers or custom RedisTemplate wrappers for Spring Data Redis Repository operations (save(), find(), etc.)

内容的提问来源于stack exchange,提问作者aspiringCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:04:16