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

相关推荐
snow@li4 小时前
Sentinel:流量防卫兵/熔断降级
sentinel
LayZhangStrive1 天前
后端通识 - 远程服务调用RPC
网络·网络协议·rpc·sentinel·openfeign·远程服务调用
她说可以呀4 天前
Sentinel 授权规则
开发语言·sentinel
她说可以呀4 天前
Sentinel 流控规则 · 流控模式
sentinel
她说可以呀5 天前
Sentinel 热点规则
sentinel
智码看视界5 天前
Day 45 | Sentinel流量治理:从限流到熔断降级再到系统自适应保护
sentinel·高并发·熔断降级·流量控制·微服务治理·热点参数限流
cfm_29146 天前
了解Sentinel
分布式·架构·sentinel
Bruce18016 天前
Sentinel 限流熔断学习:配置策略、限流算法对比与适用场景
sentinel
成为你的宁宁6 天前
【Sentinel部署与流量防护】
sentinel
952367 天前
Sentinel
java·后端·spring·sentinel·springcloud