sentinel异常处理机制

1、自动识别出来的web接口

会走BlockExceptionHandler,可自定义,例如:

java 复制代码
@Component
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s,
        BlockException e) throws Exception {
        tooFrequencyResponse(httpServletResponse);
    }

    public void tooFrequencyResponse(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); // 429状态码

        CommonResult<?> result = CommonResult.failResult(8001, "服务器繁忙,请稍后重试");
        String jsonString = JSONUtil.toJsonStr(result);
        response.getWriter().write(jsonString);
    }
}

在项目中加入此类即可生效

2、@SentinelResource标记的资源

会依次去找@SentinelResource注解里面配置的blockHandler,fallback,defaultFallback,根据先后顺序找到即对应处理,如果都未配置,则返回Springboot的默认处理

统一处理:

java 复制代码
@ExceptionHandler({UndeclaredThrowableException.class})
public CommonResult<?> flowExceptionHandler(UndeclaredThrowableException e) {
    log.error("UndeclaredThrowableException: ", e);
    return CommonResult.failResult(CommonErrorInfo.code_8001,"服务器繁忙,请稍后重试");
}

3、openfeign调用的资源

会根据设置的fallback来返回异常,如果未设置则返回Springboot的默认处理

相关推荐
Takumilove19 小时前
Spring Boot 接入 Redis Sentinel:自动主从切换与读写分离实战(修复单机多实例与 Sentinel 配置坑)
spring boot·redis·sentinel
波波烤鸭9 天前
Redis 高可用实战源码解析(Sentinel + Cluster 整合应用)
数据库·redis·sentinel
hzzzzzo011 天前
微服务保护全攻略:从雪崩到 Sentinel 实战
数据库·微服务·sentinel
没有bug.的程序员12 天前
Redis Sentinel:高可用架构的守护者
java·redis·架构·sentinel
波波烤鸭12 天前
Sentinel 原理与源码解析:流控、熔断、降级到热点限流的一体化方案
sentinel
曾经的三心草13 天前
springcloud二-Sentinel
spring·spring cloud·sentinel
T_Ghost16 天前
SpringCloud微服务服务容错机制Sentinel熔断器
spring cloud·微服务·sentinel
你是人间五月天17 天前
sentinel实现控制台与nacos数据双向绑定
windows·sentinel
无名客017 天前
sentinel限流常见的几种算法以及优缺点
算法·sentinel·限流
tsxchen17 天前
centos9安装sentinel
sentinel