sentinel异常处理机制
1、自动识别出来的web接口
会走BlockExceptionHandler,可自定义,例如:
@Component
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {@Overridepublic 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的默认处理
统一处理:
@ExceptionHandler({UndeclaredThrowableException.class})
public CommonResult<?> flowExceptionHandler(UndeclaredThrowableException e) {log.error("UndeclaredThrowableException: ", e);return CommonResult.failResult(CommonErrorInfo.code_8001,"服务器繁忙,请稍后重试");
}
3、openfeign调用的资源
会根据设置的fallback来返回异常,如果未设置则返回Springboot的默认处理