spring-boot - 如何使用 Spring Cache 处理 redis 异常?
问题描述
我目前正在开发一个包含 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在可缓存中抛出的异常?
解决方案
我相信您想定义自己的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();
}
}
推荐阅读
- javascript - Angular 和 vanila JS - 设置输入值
- python - 单元测试在 azure 管道中使用 moto 失败
- javascript - docker node js文件存储卷
- javascript - 如何在 Redux Toolkit 中使用 preloadedState
- solidity - 我得到了一些令牌代码/我需要更改方法名称
- java - 模拟 Quarkus 提供的记录器
- javascript - 使用 XLSX 将 Excel 文件内容加载并显示为 HTML 表格 Angular
- python - Django 模型无法在 html 中呈现
- windows - 如何在 Windows 中手动创建 .npmrc 文件
- ssms - 在 SSMS 中创建服务帐户失败