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

相关推荐
u0104058362 天前
Java中的服务熔断机制:Hystrix与Sentinel的比较
java·hystrix·sentinel
what丶k2 天前
微服务稳定性守护者:Sentinel 全面使用指南(从入门到企业级落地)
微服务·架构·sentinel
鸽鸽程序猿2 天前
【JavaEE】【SpringCloud】 熔断和限流 Alibaba Sentinel
spring cloud·java-ee·sentinel
小楼v2 天前
如何使用Sentinel进行流量控制和熔断
java·后端·sentinel
MediaTea5 天前
Python:_sentinel 命名约定
开发语言·python·sentinel
短剑重铸之日6 天前
《SpringCloud实用版》Feign + LoadBalancer + Sentinel 微服务调用链路
spring cloud·微服务·sentinel·feign·loadbalancer
短剑重铸之日6 天前
《SpringCloud实用版》告别 Hystrix!Sentinel vs Resilience4j 深度对比 & 选型
spring cloud·hystrix·sentinel·熔断限流降级
wfsm9 天前
sentinel
sentinel
sunnyday042611 天前
Spring Cloud Alibaba Sentinel 流量控制与熔断降级实战指南
spring boot·sentinel·springcloud
递归尽头是星辰14 天前
Spring Cloud Alibaba 核心理论体系:Nacos、Sentinel、Seata深度解析
spring cloud·nacos·sentinel·seata·微服务治理