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

相关推荐
廋到被风吹走5 天前
稳定性保障:限流降级深度解析 —— Sentinel滑动窗口算法与令牌桶实现
运维·算法·sentinel
笨蛋不要掉眼泪9 天前
Sentinel 热点参数限流实战:精准控制秒杀接口的流量洪峰
java·前端·分布式·spring·sentinel
笨蛋不要掉眼泪10 天前
Sentinel 流控规则详解:三种模式与三种效果实战指南
java·jvm·数据库·后端·sentinel
Jinkxs11 天前
Sentinel - 在 Dubbo 微服务中使用:Alibaba 生态无缝集成
微服务·sentinel·dubbo
笨蛋不要掉眼泪11 天前
Spring Cloud Alibaba Sentinel 从入门到实战:微服务稳定性的守护者
分布式·微服务·云原生·架构·sentinel
tod11311 天前
Redis Sentinel 高可用架构:从原理到 Docker 部署全解析
数据库·redis·docker·架构·sentinel
递归尽头是星辰13 天前
Sentinel + Spring Cloud Gateway 联动限流实战
系统架构·sentinel·限流·微服务治理·限流架构设计
万象.13 天前
redis哨兵sentinel的部署及作用
redis·sentinel
七夜zippoe14 天前
分布式系统弹性设计实战:Hystrix与Sentinel熔断降级深度解析
java·hystrix·sentinel·aws·分布式系统
程序员敲代码吗15 天前
微服务熔断降级配置详解与实践:使用Sentinel和Nacos
java·微服务·sentinel