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

相关推荐
孤狼程序员14 小时前
【Spring Cloud微服务】8.深度实战:微服务稳定性的守护神——Sentinel
spring cloud·微服务·sentinel
the beard2 天前
Feign整合Sentinel实现服务降级与Feign拦截器实战指南
java·spring·sentinel
微扬嘴角6 天前
springcloud篇5-微服务保护(Sentinel)
spring cloud·微服务·sentinel
java亮小白19977 天前
Spring Cloud 快速通关之Sentinel
java·spring cloud·sentinel
银迢迢8 天前
SpringCloud微服务技术自用笔记
java·spring cloud·微服务·gateway·sentinel
西红柿维生素10 天前
Sentinel相关记录
网络·sentinel
重整旗鼓~15 天前
46.Sentinel规则持久化
sentinel
sniper_fandc17 天前
Spring Cloud系列—Alibaba Sentinel授权与规则管理及推送
spring cloud·sentinel
xiao-xiang17 天前
redis-sentinel基础概念及部署
数据库·redis·sentinel