【问题标题】:How to handle redis exceptions by using Spring Cache?如何使用 Spring Cache 处理 redis 异常?
【发布时间】:2021-04-27 09:47:20
【问题描述】:

我目前正在开发一个同时包含 Spring Data Redis 和 Spring Cache 的项目。在spring data redis中,我使用redis模板调用redis。我在 try catch 块中处理 redis 模板抛出的所有异常:

   try{
       // execute some operation with redis template
    }
    catch(RedisCommandTimeoutException ex){

    }
    catch(RedisBusyException ex){

    }
    catch(RedisConnectionFailureException ex){

    }
    catch(Exception ex){

    }

我可以使用类似的 try-catch 块来处理来自@cacheable 的异常吗?怎么处理redis在cacheable中抛出的异常?

【问题讨论】:

    标签: spring-boot redis spring-data-redis spring-cache


    【解决方案1】:

    我相信您想定义自己的 CacheErrorHandler 来处理 @Cachable@CachePut@CacheEvict

    您将定义CacheErrorHandler

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.cache.Cache;
    import org.springframework.cache.interceptor.CacheErrorHandler;
    
    @Slf4j
    public class CustomCacheErrorHandler implements CacheErrorHandler {
        @Override
        public void handleCacheGetError(RuntimeException e, Cache cache, Object o) {
            log.error(e.getMessage(), e);
        }
    
        @Override
        public void handleCachePutError(RuntimeException e, Cache cache, Object o, Object o1) {
            log.error(e.getMessage(), e);
        }
    
        @Override
        public void handleCacheEvictError(RuntimeException e, Cache cache, Object o) {
            log.error(e.getMessage(), e);
        }
    
        @Override
        public void handleCacheClearError(RuntimeException e, Cache cache) {
            log.error(e.getMessage(), e);
        }
    }
    

    然后注册:

    import org.springframework.cache.annotation.CachingConfigurerSupport;  
    import org.springframework.cache.interceptor.CacheErrorHandler;  
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class CachingConfiguration extends CachingConfigurerSupport {  
        @Override
        public CacheErrorHandler errorHandler() {
            return new CustomCacheErrorHandler();
        }
    }
    

    【讨论】:

    • 你能多谈谈 Jedis 驱动抛出的异常吗?如果我使用 Jedis,我在哪里可以找到有关异常处理的文档?
    • 如果您使用的是 spring 可缓存注释,我想您定义的 CacheErrorHandler 将捕获底层驱动程序提供程序抛出的异常。 (你的绝地武士)
    • 如何检查抛出了哪些异常?
    • 在不测试自己的情况下,我会执行上述操作,打开应用程序,然后尝试引发问题。 (例如,在尝试缓存放置时关闭 redis)您应该能够从日志输出中看到 CustomCacheErrorHandler 是否按预期工作。
    猜你喜欢
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 2016-01-20
    • 2012-11-25
    • 2019-07-21
    相关资源
    最近更新 更多