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的默认处理

相关推荐
库库林_沙琪马13 小时前
3、Sentinel
服务器·网络·sentinel
大大大大物~1 天前
Spring Cloud熔断与降级:核心区别与实践指南【怎么理解?解决了什么问题?各自的适用场景?Sentinel实现代码示例】
spring cloud·sentinel·熔断·降级
serendipity_hky1 天前
【SpringCloud | 第3篇】Sentinel 服务保护(限流、熔断降级)
java·后端·spring·spring cloud·微服务·sentinel
小毅&Nora2 天前
【后端】【诡秘架构】 ② 序列8:小丑 - 熔断降级的艺术:用 Sentinel 实现优雅降级,笑对流量洪峰
架构·sentinel·熔断降级
Haooog3 天前
微服务保护学习
java·学习·微服务·sentinel
布茹 ei ai3 天前
5、基于 GEE 的 Sentinel-1 SAR 地震滑坡变化检测系统:2022 泸定地震案例
javascript·sentinel·遥感·gee·云平台
lang201509283 天前
深入解析Sentinel熔断器核心机制
sentinel
lang201509284 天前
Sentinel系统保护规则深度解析
sentinel
lang201509284 天前
深入解析Sentinel熔断机制
java·前端·sentinel
lang201509284 天前
Sentinel熔断降级核心:DegradeSlot解析
sentinel