业务场景: 在Spring Boot项目中使用了@Cacheable注解实现往Redis中存入数据库查询数据和读取缓存数据,如果由于一些原因Redis无法连接的话,那么@Cacheable标注的方法则会报错且无法返回数据。需要在Redis无法连接的情况下让方法直接请求数据库。
解决方法: 添加Redis配置类继承CachingConfigurerSupport类,重写errorHandler方法即可。
代码如下:
@Slf4j
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* 配置当redis连接不上时被缓存注解标注的方法绕过Redis
*/
@Bean
@Override
public CacheErrorHandler errorHandler() {
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
@Override
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
log.error("redis异常:key=[{}]", key, exception);
}
@Override
public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
log.error("redis异常:key=[{}]", key, exception);
}
@Override
public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
log.error("redis异常:key=[{}]", key, exception);
}
@Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
log.error("redis异常:", exception);
}
};
return cacheErrorHandler;
}
}
本文介绍在SpringBoot项目中使用@Cacheable注解时,如何处理Redis连接失败的情况,确保方法能直接请求数据库,避免服务中断。通过自定义错误处理器,实现优雅的异常处理。
4690

被折叠的 条评论
为什么被折叠?



