如何使用 Spring Cache 处理 redis 异常?

问题描述

我目前正在开展一个项目,该项目结合了 Spring Data redis 和 Spring Cache。在 spring 数据 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 在可缓存中抛出的异常?

解决方法

我相信您想定义自己的 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,Object o,Object o1) {
        log.error(e.getMessage(),e);
    }

    @Override
    public void handleCacheEvictError(RuntimeException e,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();
    }
}