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

相关推荐
yzp-14 小时前
Sentinel 执行流程
sentinel
停水咋洗澡2 天前
Redis Sentinel高可用实战:主从自动故障转移
java·redis·sentinel
鬼先生_sir2 天前
SpringCloud-Sentinel(熔断降级 & 流量控制)
spring·spring cloud·sentinel
会飞的大可9 天前
Redis Sentinel 高可用方案在WMS仓储管理系统的应用
redis·sentinel
zs宝来了10 天前
Redis 哨兵机制:Sentinel 原理与高可用实现
redis·sentinel·高可用·源码解析·哨兵
梵得儿SHI11 天前
SpringCloud 秒杀系统生产级落地:Sentinel+Redis 联合优化,从限流防刷到库存闭环,彻底解决超卖 / 宕机 / 恶意刷
redis·spring cloud·sentinel·分布式限流·百万级·瞬时高并发·产级秒杀系统解决方案
8Qi812 天前
Redis哨兵模式(Sentinel)深度解析
java·数据库·redis·分布式·缓存·sentinel
无名-CODING12 天前
Java 爬虫零基础入门:从 HTTP 到 Jsoup 实战
spring cloud·gateway·sentinel
会飞的大可13 天前
Spring Cloud Alibaba全景:Nacos、Sentinel、Seata整合实战
sentinel·wpf
无名-CODING13 天前
SpringCloud 网关与熔断:Gateway + Sentinel 快速入门
spring cloud·gateway·sentinel