开发者社区 > 云原生 > 正文

@SentinelResource 注解 fallback 的含义

使用Sentinel注解,配置了fallback,发现throw exception不起作用,通过阅读源码

@Aspect public class SentinelResourceAspect { ....

    try {
        ContextUtil.enter(resourceName);
        entry = SphU.entry(resourceName, entryType);
        Object result = pjp.proceed();
        return result;
    } catch (BlockException ex) {
        return handleBlockException(pjp, annotation, ex);
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }

只有在捕获 BlockException 时才进入handleBlockException

private Object handleBlockException(ProceedingJoinPoint pjp, SentinelResource annotation, BlockException ex) throws Exception { // Execute fallback for degrading if configured. Object[] originArgs = pjp.getArgs(); if (isDegradeFailure(ex)) { Method method = extractFallbackMethod(pjp, annotation.fallback()); if (method != null) { return method.invoke(pjp.getTarget(), originArgs); } } // Execute block handler if configured. Method blockHandler = extractBlockHandlerMethod(pjp, annotation.blockHandler(), annotation.blockHandlerClass()); if (blockHandler != null) { // Construct args. Object[] args = Arrays.copyOf(originArgs, originArgs.length + 1); args[args.length - 1] = ex; if (isStatic(blockHandler)) { return blockHandler.invoke(null, args); } return blockHandler.invoke(pjp.getTarget(), args); } // If no block handler is present, then directly throw the exception. throw ex; }

换句话说,@SentinelResource的fallback只在抛出BlockException时才会触发fallback等相关策略?

原提问者GitHub用户anjia0532

展开
收起
码字王 2023-05-19 19:31:37 154 0
1 条回答
写回答
取消 提交回答
  • 如果设计的初衷即是如此,那么建议在wiki进行标明,因为从hystrix转过来的人会假定,fallback即为函数异常(超时,exception,降级,熔断)后执行的兜底函数。会像我一样,误以为是bug,但是其实是feature。

    原回答者GitHub用户anjia0532

    2023-05-19 22:46:21
    赞同 展开评论 打赏
问答分类:
问答地址:

阿里云拥有国内全面的云原生产品技术以及大规模的云原生应用实践,通过全面容器化、核心技术互联网化、应用 Serverless 化三大范式,助力制造业企业高效上云,实现系统稳定、应用敏捷智能。拥抱云原生,让创新无处不在。

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载