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

相关推荐
空中海4 天前
第六篇:可靠性篇 — Sentinel 熔断限流与 Seata 分布式事务
分布式·sentinel
JAVA面经实录9174 天前
如何选择适合项目的「限流 / 熔断 / 降级」方案
java·spring·kafka·sentinel·guava
蓝眸少年CY6 天前
(第十五篇)spring cloud之Sentinel实现熔断与限流
数据库·spring cloud·sentinel
无风听海8 天前
Python 哨兵值模式(Sentinel Value Pattern)深度解析
开发语言·python·sentinel
空中海9 天前
Redis 原理深度解析:持久化 × 主从复制 × Sentinel × Cluster × 性能排查全攻略
数据库·redis·sentinel
接着奏乐接着舞11 天前
Sentinel
sentinel
随风,奔跑11 天前
Spring Boot Alibaba(三)----Sentinel
spring boot·后端·sentinel
武超杰11 天前
Sentinel 安装启动 + 全规则详解 + Feign 整合 + 持久化
sentinel
青槿吖11 天前
Sentinel 进阶实战:Feign 整合 + 全局异常 + Nacos 持久化,生产环境直接用
java·开发语言·spring cloud·微服务·云原生·ribbon·sentinel
StackNoOverflow11 天前
Sentinel服务保护框架完全指南:从原理到实践
java·数据库·sentinel