← 全部文章ENGINEERING NOTES

Sentinel 的 blockHandler 和 fallback:签名写错不报错,等到限流那一刻才出事

本文目录
  1. 切面就是一个 try 包住两段代码
  2. 签名:参数逐个完全相同
  3. 为什么调用方拿到的是 UndeclaredThrowableException
  4. 只在第一次触发时解析,找不到只写一行 WARN
  5. 异常怎么分流
  6. fallback 兜住了,熔断照样算
  7. 嵌套资源:下游被拦,上游的 handler 在响应
  8. 代理的边界
  9. 两个随调用顺序变化的缓存坑
  10. 启动时校验
  11. 完整示例
  12. 小结

下面这段代码能编译、能启动,平时调用一切正常:

@SentinelResource(value = "queryOrder", blockHandler = "queryOrderBlocked")
public Order queryOrder(String id) { ... }

// BlockException 也是 Exception,写宽一点应该没问题吧
public Order queryOrderBlocked(String id, Exception e) {
    return Order.EMPTY;
}

直到流量上来、规则真的拦下请求,调用方拿到的不是 Order.EMPTY,而是一个 UndeclaredThrowableException,catch (BlockException e) 接不住它。到了 Web 层,@ExceptionHandler(BlockException.class) 能不能接住,要看同一个 @ControllerAdvice 里有没有更宽的处理器、advice 之间谁的优先级高:它和常见的兜底 @ExceptionHandler(Exception.class) 写在同一个 advice 里时,兜底处理器会先把异常截走,接口返回 500。应用日志里没有一行和 Sentinel 有关的错误。

原因是 @SentinelResource 的 blockHandler / fallback 既不经过编译器检查,也不在启动时绑定,而是在第一次被拦、第一次失败时用反射按名字和参数表去找。参数类型必须逐个完全相同,Exception 不等于 BlockException。找不到时它不报错,只在 Sentinel 自己的 sentinel-record.log 里写一行 WARN,然后退到下一级处理,最后把 BlockException 原样抛出。

这篇把注解切面这条路径从头走一遍:handler 怎么找、找不到会怎样、异常怎么分进 fallback 和统计、exceptionsToIgnore 该放什么、为什么同类调用会让整个注解失效,以及两个随调用顺序变化的缓存坑。每个结论都用一个可独立运行的示例验证过:完整代码在文末,九组实验,每一项都有断言,结果不符合预期时进程以 1 退出。

版本:Sentinel 1.8.10(写这篇时 Maven Central 上最新的稳定版;主干 1.8.11-SNAPSHOT 里这部分代码和 1.8.10 相同),Spring Boot 4.2.0(Spring Framework 7.1.0,AspectJ weaver 1.9.27),JDK 21。用 Spring Cloud Alibaba 时,它的 SentinelAutoConfiguration 注册的也是同一个 SentinelResourceAspect;2025.1.0.0 依赖的 Sentinel 1.8.9 在注解模块上和 1.8.10 没有差别。

切面就是一个 try 包住两段代码

SentinelResourceAspect 的核心方法(1.8.10,省略了开头取注解的几行):

Entry entry = null;
try {
    entry = SphU.entry(resourceName, resourceType, entryType, pjp.getArgs());
    return pjp.proceed();
} catch (BlockException ex) {
    return handleBlockException(pjp, annotation, ex);
} catch (Throwable ex) {
    Class<? extends Throwable>[] exceptionsToIgnore = annotation.exceptionsToIgnore();
    // The ignore list will be checked first.
    if (exceptionsToIgnore.length > 0 && exceptionBelongsTo(ex, exceptionsToIgnore)) {
        throw ex;
    }
    if (exceptionBelongsTo(ex, annotation.exceptionsToTrace())) {
        traceException(ex);
        return handleFallback(pjp, annotation, ex);
    }

    // No fallback function can handle the exception, so throw it out.
    throw ex;
} finally {
    if (entry != null) {
        entry.exit(1, pjp.getArgs());
    }
}

后面所有现象都来自这里的三个细节:

  1. SphU.entry 和 pjp.proceed()(也就是业务方法本身)在同一个 try 里。catch (BlockException ex) 不区分这个异常是当前资源的规则抛的,还是从业务方法里冒出来的。
  2. 业务异常先过 exceptionsToIgnore,再过 exceptionsToTrace(默认 {Throwable.class})。两次判断都是 exceptionClass.isAssignableFrom(ex.getClass()),只看异常自己的类,不看 cause。
  3. traceException 在 handleFallback 之前。不管 fallback 兜没兜住,异常都已经记在这次 Entry 上,exit 时进统计、进熔断器。

handler 的查找分级进行。被拦(BlockException)时依次找 blockHandler、fallback、defaultFallback,都没有就原样抛出;业务异常时依次找 fallback、defaultFallback,都没有就原样抛出。这里的“没有”不只是没配,配了但签名不匹配也算没有。

签名:参数逐个完全相同

查找逻辑在 AbstractSentinelAspectSupport#findMethod,判断条件只有一处:

if (name.equals(method.getName()) && checkStatic(mustStatic, method)
    && returnType.isAssignableFrom(method.getReturnType())
    && Arrays.equals(parameterTypes, method.getParameterTypes())) {

参数表用 Arrays.equals 比较 Class 对象,没有任何“兼容”的余地;返回类型用 isAssignableFrom,handler 可以返回原方法返回类型的子类。各种 handler 期望的参数表:

handler 期望的参数表 在哪个类里找
blockHandler 原参数 + BlockException 默认目标类;配了 blockHandlerClass 就只看数组里的第一个类,方法必须是 static
fallback 原参数;找不到再试原参数 + Throwable 默认目标类;配了 fallbackClass 同理
defaultFallback 空参数;找不到再试只有一个 Throwable 同 fallback;方法上没写时用类上 @SentinelResource 的

当前类找不到时沿父类往上找,不看接口,所以接口里的 default 方法不算数。

实验一里带 sig. 前缀的资源都配了 count = 0 的 QPS 规则,每次调用都会被拦;fb. 前缀的几个没有规则,业务方法自己抛 IllegalStateException:

  S1 正确:(String, BlockException)               返回 blockHandler(FlowException)
  S2 末参数写成 Exception                           抛出 UndeclaredThrowableException(cause FlowException)
  S3 末参数写成 FlowException                       抛出 UndeclaredThrowableException(cause FlowException)
  S4 原参数 long,handler 写 Long                   抛出 UndeclaredThrowableException(cause FlowException)
  S5 原返回 CharSequence,handler 返回 String        返回 blockHandler(FlowException)
  S6 原返回 int,handler 返回 Integer                抛出 UndeclaredThrowableException(cause FlowException)
  S7 blockHandlerClass 里的实例方法                  抛出 UndeclaredThrowableException(cause FlowException)
  S8 blockHandlerClass 里的 static 方法            返回 blockHandler(FlowException)
  S9 blockHandler 写错,但有 fallback               返回 fallback(FlowException)
  S10 private 的 blockHandler                   返回 blockHandler(FlowException)
  F1 fallback 末参数写成 Exception                  抛出 IllegalStateException
  F2 fallback 只写原参数                            返回 fallback(拿不到异常)
  F3 fallback 写错,另有 defaultFallback            返回 defaultFallback(IllegalStateException)

逐条看:

  • 最后一个参数只能写 BlockException。写成父类 Exception(S2)、写成子类 FlowException(S3)都找不到。想区分限流和熔断,在 handler 里用 instanceof。
  • 基本类型和包装类型不通用(S4、S6)。long 参数配 Long、int 返回值配 Integer,源码层面有自动装箱,在反射匹配里却是不同的 Class。
  • 返回类型可以更窄(S5)。原方法返回 CharSequence,handler 返回 String 能匹配。官方文档说返回类型“需要与原方法相匹配”,实际规则比这宽一点。
  • blockHandlerClass 里只认 static 方法(S7、S8)。文档写了这一条,但忘写 static 的后果和签名写错一样,是静默的。
  • blockHandler 写错会悄悄落到 fallback(S9),fallback 收到的是 FlowException。看上去也算兜住了,但 fallback 往往是为业务失败写的:打错误日志、触发报警、返回缓存数据。限流本来是正常的保护动作,现在每一次都被当成故障处理。
  • fallback 额外的那个参数必须正好是 Throwable(F1)。写成 Exception 两种参数表都对不上,业务异常原样抛出。文档的说法是“可以额外多一个 Throwable 类型的参数用于接收对应的异常”,这里的 Throwable 要按字面理解。
  • F2:只写原参数的 fallback 能匹配,但拿不到异常,排查问题时只知道走了降级,不知道为什么。

另外两处文档和代码不一致的地方。文档说 blockHandler 的访问范围需要是 public,代码从 1.8.2 起(#2163)调用前会 setAccessible(true),private 也能用(S10)。文档说同时配了 fallback 和 defaultFallback 时只有 fallback 生效,准确地说是 fallback 找到了才只有它生效;fallback 签名写错时会接着去找 defaultFallback(F3),这时用的是通用的兜底逻辑,而你以为在用专门写的那个。

为什么调用方拿到的是 UndeclaredThrowableException

三级都找不到时,切面把 BlockException 原样抛出。它继承的是 Exception,是受检异常,而业务方法通常不会声明 throws BlockException。方法抛出了自己没声明的受检异常,Spring AOP 的代理会把它包成 java.lang.reflect.UndeclaredThrowableException。实验里用的是 CGLIB 代理(Spring Boot 的默认);JDK 动态代理在 java.lang.reflect.Proxy 这一层也是同样的规则,见 UndeclaredThrowableException 的 Javadoc。

所以在 Java 代码里直接调用这个方法的地方,catch (BlockException e) 接不住它,要接得写 UndeclaredThrowableException,再看 getCause() 是不是 BlockException。

Spring MVC 的 @ExceptionHandler 不一样,它不只看最外层的异常。Spring Framework 的文档写得很清楚:异常可以匹配最外层,也可以匹配包装异常里的 cause,“As of 5.3, this can match at arbitrary cause levels”;同一个 controller 或 @ControllerAdvice 类里,最外层的匹配优先于 cause 的匹配;而在多个 advice 之间,“a cause match on a higher-priority @ControllerAdvice bean is preferred to any match (for example, root) on a lower-priority @ControllerAdvice bean”(文档,页面版本 7.1.0)。

实验七用同一个版本跑了一遍:五个接口都调用 S2 那个签名写错的方法,区别只在各自生效的处理器(每个 advice 用 assignableTypes 限定到一个接口,M4、M5 的两个 advice 用 @Order 排优先级):

  M1 没有任何 @ExceptionHandler                    HTTP 500
  M2 只有 BlockException 处理器                     HTTP 429 BlockException 处理器(参数实际是 FlowException)
  M3 同一个 advice 里还有 Exception 处理器              HTTP 500 Exception 处理器(参数实际是 UndeclaredThrowableException)
  M4 Exception 处理器在优先级更高的 advice               HTTP 500 Exception 处理器(参数实际是 UndeclaredThrowableException)
  M5 BlockException 处理器在优先级更高的 advice          HTTP 429 BlockException 处理器(参数实际是 FlowException)
  • 只有 BlockException 处理器时(M2),它能接住被包装的异常,而且方法参数拿到的是 cause 本身(FlowException),不是外面那层。
  • 同一个 advice 里还有 Exception 处理器时(M3),最外层的 UndeclaredThrowableException 直接匹配上 Exception,BlockException 处理器不会被用到。很多项目的全局异常处理正是这样写的。
  • 分在两个 advice 里时,谁的优先级高谁赢(M4、M5)。想让限流在 Web 层稳定地变成 429,BlockException 处理器要放在一个优先级比所有宽泛处理器都高的 advice 里。
  • 什么都没写时(M1),Spring Boot 默认的错误处理返回 500。

这些规则能补救一部分,但补救的只是 HTTP 响应。blockHandler 里的降级逻辑照样没有执行,非 Web 的调用方(定时任务、消息消费者、RPC 提供端)也用不上这套机制。更好的办法是让签名一开始就写对,后面“启动时校验”一节给了一个做法。

只在第一次触发时解析,找不到只写一行 WARN

解析结果缓存在 ResourceMetadataRegistry 的三个静态 Map 里,找不到也会缓存一个“不存在”的占位。所以每个 handler 在一个 JVM 里只解析一次,也只写一次日志。日志写进 sentinel-record.log(默认目录 ~/logs/csp/,可以用 csp.sentinel.log.dir 改),不进应用自己的日志。

更麻烦的是,解析发生在故障路径上:签名写错的 blockHandler 只有在规则第一次真的拦下请求时才会被发现,正是你最需要它的时候。

实验八把整次运行里的 Cannot find 都收集了出来:

    Cannot find method [exParamBlocked] in class [demo.SignatureService] with parameters [class java.lang.String, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find method [flowParamBlocked] in class [demo.SignatureService] with parameters [class java.lang.String, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find method [boxedParamBlocked] in class [demo.SignatureService] with parameters [long, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find method [boxedReturnBlocked] in class [demo.SignatureService] with parameters [class java.lang.String, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find static method [instanceHandler] in class [demo.Handlers] with parameters [class java.lang.String, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find method [toFallbackBlocked] in class [demo.SignatureService] with parameters [class java.lang.String, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find method [toFallbackFallback] in class [demo.SignatureService] with parameters [class java.lang.String]
    Cannot find method [fbExParamFallback] in class [demo.SignatureService] with parameters [class java.lang.String]
    Cannot find method [fbExParamFallback] in class [demo.SignatureService] with parameters [class java.lang.String, class java.lang.Throwable]
    Cannot find method [fbToDefaultFallback] in class [demo.SignatureService] with parameters [class java.lang.String]
    Cannot find method [fbToDefaultFallback] in class [demo.SignatureService] with parameters [class java.lang.String, class java.lang.Throwable]
    Cannot find method [fbDefault] in class [demo.SignatureService] with parameters []
    Cannot find method [fb] in class [demo.ExceptionService] with parameters [class java.lang.String]
    Cannot find method [fbRethrowError] in class [demo.ExceptionService] with parameters [class java.lang.String]
    Cannot find method [fb] in class [demo.QueryService] with parameters [class java.lang.String]
    Cannot find method [fb] in class [demo.OuterService] with parameters []
    Cannot find method [annotatedFallback] in class [demo.SelfCallService] with parameters []
    Cannot find method [df] in class [demo.ReportServiceA] with parameters []
    Cannot find method [df] in class [demo.ReportServiceB] with parameters []
    Cannot find method [df] in class [demo.ReportServiceB] with parameters [class java.lang.Throwable]
    Cannot find method [fb] in class [demo.ReportServiceC] with parameters [class java.lang.String]
  WARN 行数                                      21

21 行里真正有问题的是 12 行:S2、S3、S4、S6、S7、S9 的 blockHandler 各一行,F1、F3 的 fallback 各两行(两种参数表各找了一次),D2 的 defaultFallback 两行(后面会讲)。另外 9 行来自配置正确的 fallback 和 defaultFallback:带 Throwable 参数的写法会先按不带 Throwable 的参数表找一次,找不到就写一行 WARN,再去找第二种。也就是说,按文档推荐的写法接收异常的每一个 fallback,第一次触发时都会留下一行看起来像错误的日志。靠 grep 这个文件发现配置错误不现实。

异常怎么分流

实验二的几个资源都没有流控规则,业务方法按参数抛出不同的异常:

  E1 默认 + IllegalStateException                返回 fallback(IllegalStateException)
  E1 默认 + BadRequestException                  返回 fallback(BadRequestException)
  E1 默认 + OutOfMemoryError                     返回 fallback(OutOfMemoryError)
  E1 ex.default 记录的异常数                         异常 3
  E2 ignore + BadRequestException              抛出 BadRequestException
  E2 ignore + 子类 MissingParamException         抛出 MissingParamException
  E2 ignore + 被包了一层的 BadRequestException       返回 fallback(IllegalStateException)
  E2 ignore + IllegalStateException            返回 fallback(IllegalStateException)
  E2 ex.ignore 记录的异常数                          异常 2
  E3 traceIo + UncheckedIOException            返回 fallback(UncheckedIOException)
  E3 traceIo + IllegalStateException           抛出 IllegalStateException
  E3 ex.traceIo 记录的异常数                         异常 1
  E4 fallback 遇到 Error 原样抛出                    抛出 OutOfMemoryError
  E4 普通异常照常兜底                                  返回 fallback(IllegalStateException)
  E4 ex.rethrowError 记录的异常数                    异常 2
  • 默认连 Error 也进 fallback(E1)。exceptionsToTrace 的默认值是 {Throwable.class},业务方法抛出的 OutOfMemoryError 被 fallback 变成了一个普通的返回值,调用方拿着降级结果继续往下跑。注意 E1 里的 OutOfMemoryError 是代码自己 new 出来抛的,只验证了注解怎么给 Error 分流;真实的堆耗尽时 fallback 能不能执行、执行之后应用处在什么状态,这里没有验证。如果 fallback 只想处理异常,就在里面把 Error 原样抛出(E4)。异常在调 fallback 之前就记过了,E4 的两次失败都在统计里,熔断不受影响。不要为此把 Error 放进 exceptionsToIgnore,那样它就不进统计了。

  • exceptionsToIgnore 按继承匹配,但只看异常自己的类(E2)。子类 MissingParamException 也被忽略;IllegalStateException 里包着一个 BadRequestException 就不算,照样进 fallback、照样记异常。习惯把异常包一层再抛的代码,要忽略的是外面那一层。

  • 被忽略的异常原样抛给调用方,不进 fallback,也不记异常(E2 只记了两次,都是没被忽略的那两次)。对熔断器来说,这次请求的 Entry 上没有 error,就是一次正常完成的请求:异常数不算它,异常比例的分母反而算它。ExceptionCircuitBreaker#onRequestComplete 里是这样记的:

    if (error != null) {
        counter.getErrorCount().add(1);
    }
    counter.getTotalCount().add(1);
  • 自己写了 exceptionsToTrace,它就成了白名单(E3)。只追踪 IO 类异常时,IllegalStateException 既不记、也不进 fallback,直接抛出。

fallback 兜住了,熔断照样算

实验三的两个资源都配了“统计窗口内异常数大于 2 就熔断 30 秒”的规则。先用空 id 调 5 次(参数错误),再用正常 id 调 1 次:

  B1 默认:5 次空 id,再 1 次正常 id
      第 1 次                                    返回 fallback(BadRequestException)
      第 2 次                                    返回 fallback(BadRequestException)
      第 3 次                                    返回 fallback(BadRequestException)
      第 4 次                                    返回 blockHandler(DegradeException)
      第 5 次                                    返回 blockHandler(DegradeException)
      第 6 次                                    返回 blockHandler(DegradeException)
  B2 忽略 BadRequestException:同样 6 次
      第 1 次                                    抛出 BadRequestException
      第 2 次                                    抛出 BadRequestException
      第 3 次                                    抛出 BadRequestException
      第 4 次                                    抛出 BadRequestException
      第 5 次                                    抛出 BadRequestException
      第 6 次                                    返回 ok:42

默认配置下,前三次走 fallback,调用方看到的都是正常返回值。第三次之后异常数 3 > 2,熔断器打开;第 4、5 次连同那次参数正确的请求都被 DegradeException 拦下,进了 blockHandler。接下来 30 秒,这个资源上的所有请求都拿到降级结果,起因只是某个调用方在传空参数。

把 BadRequestException 放进 exceptionsToIgnore 之后,参数错误原样抛给调用方,熔断器不受影响,正常请求照常返回。

这就是 exceptionsToIgnore 该放什么的答案:放“调用方的错”,比如参数校验失败、资源不存在、无权限、被业务规则拒绝(余额不足之类)。这些异常恰恰说明被保护的依赖是健康的。代价是它们不再进 fallback,要由调用方或全局异常处理来接;通常本来就该这样,参数错误不应该被降级成一个默认值。反过来,超时、连接失败、下游 5xx 这类“依赖出了问题”的异常要留在统计里,熔断才有意义。

嵌套资源:下游被拦,上游的 handler 在响应

这是第一个细节的后果。实验四里 OuterService 的两个方法都标了资源,自己没有任何规则,各自调用 InnerService 的一个资源;inner 的两个资源配了 count = 0,而且没写任何 handler:

  N1 下游声明 throws BlockException                返回 outer.blockHandler(FlowException 来自 inner.declared)
  N1 outer.declared 通过/拦截/异常                   通过 1 / 拦截 0 / 异常 0
  N1 inner.declared 通过/拦截/异常                   通过 0 / 拦截 1 / 异常 0
  N2 下游没声明                                     返回 outer.fallback(UndeclaredThrowableException)
  N2 outer.undeclared 通过/拦截/异常                 通过 1 / 拦截 0 / 异常 1
  N2 inner.undeclared 通过/拦截/异常                 通过 0 / 拦截 1 / 异常 0
  • N1,下游声明了 throws BlockException。FlowException 原样穿过代理,被 outer 切面的 catch (BlockException ex) 接住,于是 outer 的 blockHandler 被调用了,尽管 outer 自己没有任何规则。统计上 outer 是“通过 1、拦截 0、异常 0”,一次成功的调用。看监控会以为 outer 从来没被限流,日志里却全是 outer 的限流处理。
  • N2,下游没声明。代理把 FlowException 包成 UndeclaredThrowableException,outer 的切面把它当成业务异常:记一次异常,进 fallback。下游的限流在上游变成了故障。outer 上要是配了异常数或异常比例的熔断规则,下游一限流,上游就跟着熔断。

处理办法:

  1. 每个资源配自己的 blockHandler,不让 BlockException 往上冒。只有这样,返回值和两边的统计才都是对的。
  2. 上游 handler 里先看清楚是谁被拦了。BlockException#getRule() 带着触发它的那条规则,N1 里 e.getRule().getResource() 是 inner.declared,不是 outer 自己。
  3. 在上游 fallback 里拆 UndeclaredThrowableException 只能改返回值:异常在调 fallback 之前已经记到 outer 上了。

代理的边界

实验五里 self.target 配了 count = 0:

  P1 同类里 this.target()                         返回 biz
  P1 self.target 节点是否存在                        false
  P2 通过代理调用 target()                           返回 blockHandler(FlowException)
  P2 self.target 节点是否存在                        true
  P3 fallback 方法自己也标了 @SentinelResource        返回 fallback
  P3 self.fallbackResource 节点是否存在              false
  • 同类里的 this.target() 不经过代理,切面根本没执行(P1)。没有 Entry,连资源节点都没有创建,ClusterBuilderSlot.getClusterNode("self.target") 返回 null。规则形同虚设,blockHandler 也不会被调用。这和 @Transactional 的同类调用失效是同一个原因,但更难察觉:事务失效时数据迟早会出问题,限流失效平时什么症状都没有,Sentinel 里压根没有这个资源。官方文档里“注解方式埋点不支持 private 方法”也是同一个原因,CGLIB 生成的子类覆盖不了 private 方法。
  • 通过代理调用就正常了(P2)。示例用 ObjectProvider<SelfCallService> 拿到容器里的代理对象。其他做法还有:把资源方法挪到另一个 bean(最清楚);用 @Lazy 注入自己;AopContext.currentProxy(),需要 @EnableAspectJAutoProxy(exposeProxy = true);或者改用 AspectJ 编译期、加载期织入,不走代理。示例只验证了 ObjectProvider 这一种。
  • handler 本身是用反射在原始对象(pjp.getTarget())上调用的,同样不经过代理(P3)。fallback 上标的 @SentinelResource 没有生效,资源节点不存在。照同样的道理,标在 handler 上的 @Transactional、@Async、@Cacheable 也不会生效;示例只验证了 @SentinelResource,其余几个是同一机制的推论。

两个随调用顺序变化的缓存坑

ResourceMetadataRegistry 用两种键缓存解析结果:

private static String getKey(Class<?> clazz, String name) {
    return String.format("%s:%s", clazz.getCanonicalName(), name);
}

private static String getKey(Class<?> clazz, String name, Class<?>[] parameterTypes) {
    return String.format(
            "%s:%s;%s",
            clazz.getCanonicalName(),
            name,
            Arrays.stream(parameterTypes).map(Class::getCanonicalName).collect(Collectors.joining(","))
    );
}

defaultFallback 用的是第一种,键里只有类名和方法名;可解析时又要拿当前方法的返回类型做 isAssignableFrom 匹配。同一个类里返回类型不同的方法共用一个 defaultFallback 时,谁先失败,谁决定缓存里放什么。实验六里 ReportServiceA 和 ReportServiceB 的代码完全相同:类上配了 defaultFallback = "df",df 返回 String,title() 返回 String,count() 返回 Integer;两个类的区别只是调用顺序:

  D1 A 先调 title()(返回 String)                   返回 defaultFallback
  D1 A 再调 count()(返回 Integer)                  抛出 ClassCastException
  D2 B 先调 count()(返回 Integer)                  抛出 IllegalStateException
  D2 B 再调 title()(返回 String)                   抛出 IllegalStateException
  D3 C 先调 title(id)(返回 String)                 返回 fallback
  D3 C 再调 count(id)(返回 Integer)                抛出 ClassCastException
  • D1:title() 先失败,解析出 String df(Throwable) 并缓存。count() 再失败时直接拿缓存里的方法调用,String 被当成 Integer 返回,代理里的强制转换抛出 ClassCastException。
  • D2:count() 先失败,按 Integer 找不到,缓存了“不存在”。之后 title() 失败,读到的也是“不存在”,原本能匹配的 defaultFallback 不再使用,异常原样抛出。

生产环境里哪个方法先失败没法预知,同一份代码重启一次,行为就可能不一样。

fallback 和 blockHandler 用第二种键,有参数类型(1.8.8 修过同名不同参的问题,#3395),但同样没有返回类型。D3 里 ReportServiceC 的两个方法参数相同、返回类型不同,共用一个返回 String 的 fallback,结果和 D1 一样。严格地说,D3 里 count 的 fallback 本来就配错了,只不过它不会表现为“找不到”,而是 ClassCastException。

结论:类级别的 defaultFallback 只用在所有方法返回同一种类型的类上,比如都返回统一的结果包装类。

启动时校验

既然 Sentinel 要等到出事时才解析,那就在启动时或测试里按同样的规则自己解析一遍。示例里的 HandlerValidator 照着 1.8.10 的 findMethod 写成:遍历容器里的每个 bean,用 AopUtils.getTargetClass 拿到代理背后的类,检查每个 @SentinelResource 方法的 blockHandler、fallback 和 defaultFallback。实验九的结果:

    ReportServiceA#count: defaultFallback df 不匹配,要求 Integer () 或 Integer (Throwable)
    ReportServiceB#count: defaultFallback df 不匹配,要求 Integer () 或 Integer (Throwable)
    ReportServiceC#count: fallback fb 不匹配,要求 Integer (String) 或 Integer (String, Throwable)
    SignatureService#boxedParam: blockHandler boxedParamBlocked 不匹配,要求 String (long, BlockException)
    SignatureService#boxedReturn: blockHandler boxedReturnBlocked 不匹配,要求 int (String, BlockException)
    SignatureService#exParam: blockHandler exParamBlocked 不匹配,要求 String (String, BlockException)
    SignatureService#fbExParam: fallback fbExParamFallback 不匹配,要求 String (String) 或 String (String, Throwable)
    SignatureService#fbToDefault: fallback fbToDefaultFallback 不匹配,要求 String (String) 或 String (String, Throwable)
    SignatureService#flowParam: blockHandler flowParamBlocked 不匹配,要求 String (String, BlockException)
    SignatureService#nonStatic: blockHandler instanceHandler 不匹配,要求 static String (String, BlockException)
    SignatureService#toFallback: blockHandler toFallbackBlocked 不匹配,要求 String (String, BlockException)
  发现的问题数                                       11

前面实验里故意写错的 11 处全部找了出来,包括 D1 那种单独看能用、换个调用顺序就坏的情况。它对每个方法单独比较 defaultFallback 和这个方法的返回类型,不受调用顺序影响。

它的局限也要说清楚:

  • 它复制了 Sentinel 的匹配规则。升级 Sentinel 时要看一下 AbstractSentinelAspectSupport 有没有变。
  • 它查不出同类调用和嵌套资源的问题。那是调用方式的问题,不是声明的问题。
  • 示例里是在实验跑完之后才调用它。放进项目时,可以写成一个启动整个容器的测试,也可以在容器启动完成后执行、发现问题就让启动失败;这两种接法示例里都没有写。

另一个办法是做一次限流演练:在测试环境给每个资源推一条 count = 0 的规则,挨个调一遍。它能顺带发现同类调用(资源节点不出现),但要覆盖所有资源和所有异常分支,成本高得多。

完整示例

需要 JDK 17 以上和 Maven 3.9。目录结构:

sentinel-handler-demo/
├── pom.xml
└── src/main/
    ├── resources/application.properties
    └── java/demo/
        ├── App.java
        ├── Scenarios.java
        ├── HandlerValidator.java
        ├── Exceptions.java
        ├── Handlers.java
        ├── SignatureService.java
        ├── ExceptionService.java
        ├── QueryService.java
        ├── InnerService.java
        ├── OuterService.java
        ├── SelfCallService.java
        ├── ReportServiceA.java
        ├── ReportServiceB.java
        ├── ReportServiceC.java
        └── MvcControllers.java

在项目根目录运行:

mvn -q spring-boot:run

全部符合预期时最后一行是“全部符合预期”,退出码 0;任何一项不符合,那一行后面会标出期望值,最后打印不符合的项数,退出码 1。程序会在 127.0.0.1 的一个随机端口上起一个 Web 服务给实验七用,跑完就退出。Sentinel 的日志写到 target/sentinel-logs/,实验八从那里数 WARN;每次启动时程序会先清空这个目录。

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.2.0</version>
    <relativePath/>
  </parent>

  <groupId>demo</groupId>
  <artifactId>sentinel-handler-demo</artifactId>
  <version>1.0</version>

  <properties>
    <java.version>17</java.version>
    <sentinel.version>1.8.10</sentinel.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aspectj</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webmvc</artifactId>
    </dependency>
    <dependency>
      <groupId>com.alibaba.csp</groupId>
      <artifactId>sentinel-annotation-aspectj</artifactId>
      <version>${sentinel.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <jvmArguments>-Dstdout.encoding=UTF-8</jvmArguments>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

application.properties:

spring.main.banner-mode=off
logging.level.root=warn
# 实验九的 M1 会让一个请求以异常结束,Tomcat 会打一整段堆栈,这里关掉
logging.level.org.apache.catalina.core=off
server.address=127.0.0.1
server.port=0

App.java:

package demo;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class App {

    public static void main(String[] args) throws Exception {
        // 必须在 Sentinel 任何类初始化之前设置:把 sentinel-record.log 放到 target 下。
        // 先清掉上一次运行的日志,实验七要数这一次运行写下的 WARN。
        Path logDir = Path.of("target", "sentinel-logs");
        if (Files.isDirectory(logDir)) {
            try (Stream<Path> files = Files.list(logDir)) {
                for (Path f : (Iterable<Path>) files::iterator) {
                    Files.delete(f);
                }
            }
        }
        System.setProperty("csp.sentinel.log.dir", logDir.toString());
        System.setProperty("project.name", "handler-demo");
        int failures;
        try (ConfigurableApplicationContext ctx = SpringApplication.run(App.class, args)) {
            failures = ctx.getBean(Scenarios.class).runAll();
        }
        System.exit(failures == 0 ? 0 : 1);
    }

    // 不用 Spring Cloud Alibaba 时,切面要自己注册
    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
}

Scenarios.java,所有实验和断言都在这里:

package demo;

import com.alibaba.csp.sentinel.node.ClusterNode;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class Scenarios {

    private final SignatureService sig;
    private final ExceptionService ex;
    private final QueryService query;
    private final OuterService outer;
    private final SelfCallService selfCall;
    private final ReportServiceA reportA;
    private final ReportServiceB reportB;
    private final ReportServiceC reportC;
    private final ApplicationContext ctx;
    private int failures;

    public Scenarios(SignatureService sig, ExceptionService ex, QueryService query, OuterService outer,
                     SelfCallService selfCall, ReportServiceA reportA, ReportServiceB reportB,
                     ReportServiceC reportC, ApplicationContext ctx) {
        this.sig = sig;
        this.ex = ex;
        this.query = query;
        this.outer = outer;
        this.selfCall = selfCall;
        this.reportA = reportA;
        this.reportB = reportB;
        this.reportC = reportC;
        this.ctx = ctx;
    }

    public int runAll() throws Exception {
        loadRules();
        signatures();
        exceptions();
        breaker();
        nested();
        proxyBoundary();
        defaultFallbackCache();
        mvc();
        recordLog();
        validator();
        System.out.println();
        System.out.println(failures == 0 ? "全部符合预期" : failures + " 项不符合预期");
        return failures;
    }

    private void loadRules() {
        List<FlowRule> flow = new ArrayList<>();
        for (String r : List.of("sig.ok", "sig.exParam", "sig.flowParam", "sig.boxedParam", "sig.narrowReturn",
            "sig.boxedReturn", "sig.nonStatic", "sig.static", "sig.toFallback", "sig.private",
            "inner.declared", "inner.undeclared", "self.target")) {
            FlowRule rule = new FlowRule(r);
            rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
            rule.setCount(0);   // 每次都拦
            flow.add(rule);
        }
        FlowRuleManager.loadRules(flow);

        List<DegradeRule> degrade = new ArrayList<>();
        for (String r : List.of("query.default", "query.ignore")) {
            DegradeRule rule = new DegradeRule(r);
            rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
            rule.setCount(2);               // 统计窗口内异常数 > 2 就熔断
            rule.setTimeWindow(30);         // 熔断 30 秒
            rule.setMinRequestAmount(1);
            rule.setStatIntervalMs(60_000);
            degrade.add(rule);
        }
        DegradeRuleManager.loadRules(degrade);
    }

    private void signatures() {
        section("一、blockHandler / fallback 的签名(sig.* 每次都被流控拦下)");
        check("S1 正确:(String, BlockException)", () -> sig.ok("42"), "返回 blockHandler(FlowException)");
        check("S2 末参数写成 Exception", () -> sig.exParam("42"),
            "抛出 UndeclaredThrowableException(cause FlowException)");
        check("S3 末参数写成 FlowException", () -> sig.flowParam("42"),
            "抛出 UndeclaredThrowableException(cause FlowException)");
        check("S4 原参数 long,handler 写 Long", () -> sig.boxedParam(42L),
            "抛出 UndeclaredThrowableException(cause FlowException)");
        check("S5 原返回 CharSequence,handler 返回 String", () -> sig.narrowReturn("42"),
            "返回 blockHandler(FlowException)");
        check("S6 原返回 int,handler 返回 Integer", () -> sig.boxedReturn("42"),
            "抛出 UndeclaredThrowableException(cause FlowException)");
        check("S7 blockHandlerClass 里的实例方法", () -> sig.nonStatic("42"),
            "抛出 UndeclaredThrowableException(cause FlowException)");
        check("S8 blockHandlerClass 里的 static 方法", () -> sig.staticOk("42"),
            "返回 blockHandler(FlowException)");
        check("S9 blockHandler 写错,但有 fallback", () -> sig.toFallback("42"), "返回 fallback(FlowException)");
        check("S10 private 的 blockHandler", () -> sig.privateHandler("42"), "返回 blockHandler(FlowException)");
        check("F1 fallback 末参数写成 Exception", () -> sig.fbExParam("42"), "抛出 IllegalStateException");
        check("F2 fallback 只写原参数", () -> sig.fbNoEx("42"), "返回 fallback(拿不到异常)");
        check("F3 fallback 写错,另有 defaultFallback", () -> sig.fbToDefault("42"),
            "返回 defaultFallback(IllegalStateException)");
    }

    private void exceptions() {
        section("二、哪些异常进 fallback、哪些算进统计(没有流控规则)");
        check("E1 默认 + IllegalStateException", () -> ex.byDefault("rt"), "返回 fallback(IllegalStateException)");
        check("E1 默认 + BadRequestException", () -> ex.byDefault("bad"), "返回 fallback(BadRequestException)");
        check("E1 默认 + OutOfMemoryError", () -> ex.byDefault("oom"), "返回 fallback(OutOfMemoryError)");
        statEx("E1 ex.default 记录的异常数", "ex.default", 3);

        check("E2 ignore + BadRequestException", () -> ex.ignore("bad"), "抛出 BadRequestException");
        check("E2 ignore + 子类 MissingParamException", () -> ex.ignore("missing"), "抛出 MissingParamException");
        check("E2 ignore + 被包了一层的 BadRequestException", () -> ex.ignore("wrapped"),
            "返回 fallback(IllegalStateException)");
        check("E2 ignore + IllegalStateException", () -> ex.ignore("rt"), "返回 fallback(IllegalStateException)");
        statEx("E2 ex.ignore 记录的异常数", "ex.ignore", 2);

        check("E3 traceIo + UncheckedIOException", () -> ex.traceIo("io"), "返回 fallback(UncheckedIOException)");
        check("E3 traceIo + IllegalStateException", () -> ex.traceIo("rt"), "抛出 IllegalStateException");
        statEx("E3 ex.traceIo 记录的异常数", "ex.traceIo", 1);

        check("E4 fallback 遇到 Error 原样抛出", () -> ex.rethrowError("oom"), "抛出 OutOfMemoryError");
        check("E4 普通异常照常兜底", () -> ex.rethrowError("rt"), "返回 fallback(IllegalStateException)");
        statEx("E4 ex.rethrowError 记录的异常数", "ex.rethrowError", 2);
    }

    private void breaker() {
        section("三、被 fallback 兜住的异常照样触发熔断(异常数 > 2 熔断 30 秒)");
        List<String> withDefault = new ArrayList<>();
        List<String> withIgnore = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            withDefault.add(outcome(() -> query.query("")));
            withIgnore.add(outcome(() -> query.queryIgnoringBadRequest("")));
        }
        withDefault.add(outcome(() -> query.query("42")));
        withIgnore.add(outcome(() -> query.queryIgnoringBadRequest("42")));
        checkList("B1 默认:5 次空 id,再 1 次正常 id", withDefault, List.of(
            "返回 fallback(BadRequestException)", "返回 fallback(BadRequestException)",
            "返回 fallback(BadRequestException)", "返回 blockHandler(DegradeException)",
            "返回 blockHandler(DegradeException)", "返回 blockHandler(DegradeException)"));
        checkList("B2 忽略 BadRequestException:同样 6 次", withIgnore, List.of(
            "抛出 BadRequestException", "抛出 BadRequestException", "抛出 BadRequestException",
            "抛出 BadRequestException", "抛出 BadRequestException", "返回 ok:42"));
    }

    private void nested() {
        section("四、下游资源被拦,上游的 handler 被谁调用(只有 inner.* 有规则)");
        check("N1 下游声明 throws BlockException", outer::callDeclared, "返回 outer.blockHandler(FlowException 来自 inner.declared)");
        stat("N1 outer.declared 通过/拦截/异常", "outer.declared", 1, 0, 0);
        stat("N1 inner.declared 通过/拦截/异常", "inner.declared", 0, 1, 0);
        check("N2 下游没声明", outer::callUndeclared, "返回 outer.fallback(UndeclaredThrowableException)");
        stat("N2 outer.undeclared 通过/拦截/异常", "outer.undeclared", 1, 0, 1);
        stat("N2 inner.undeclared 通过/拦截/异常", "inner.undeclared", 0, 1, 0);
    }

    private void proxyBoundary() {
        section("五、代理的边界(self.target 每次都被拦)");
        check("P1 同类里 this.target()", selfCall::viaThis, "返回 biz");
        checkEq("P1 self.target 节点是否存在", String.valueOf(node("self.target") != null), "false");
        check("P2 通过代理调用 target()", selfCall::viaProxy, "返回 blockHandler(FlowException)");
        checkEq("P2 self.target 节点是否存在", String.valueOf(node("self.target") != null), "true");
        check("P3 fallback 方法自己也标了 @SentinelResource", selfCall::failing, "返回 fallback");
        checkEq("P3 self.fallbackResource 节点是否存在",
            String.valueOf(node("self.fallbackResource") != null), "false");
    }

    private void defaultFallbackCache() {
        section("六、类级 defaultFallback 的缓存只按名字(df 返回 String)");
        check("D1 A 先调 title()(返回 String)", reportA::title, "返回 defaultFallback");
        check("D1 A 再调 count()(返回 Integer)", reportA::count, "抛出 ClassCastException");
        check("D2 B 先调 count()(返回 Integer)", reportB::count, "抛出 IllegalStateException");
        check("D2 B 再调 title()(返回 String)", reportB::title, "抛出 IllegalStateException");
        check("D3 C 先调 title(id)(返回 String)", () -> reportC.title("42"), "返回 fallback");
        check("D3 C 再调 count(id)(返回 Integer)", () -> reportC.count("42"), "抛出 ClassCastException");
    }

    private void mvc() throws Exception {
        section("七、同一个异常到了 Spring MVC 的 @ExceptionHandler(sig.exParam 的 blockHandler 签名是错的)");
        String base = "http://127.0.0.1:" + ctx.getEnvironment().getProperty("local.server.port");
        HttpClient http = HttpClient.newBuilder()
            .proxy(HttpClient.Builder.NO_PROXY)
            .connectTimeout(Duration.ofSeconds(2))
            .build();
        checkEq("M1 没有任何 @ExceptionHandler", httpGet(http, base + "/mvc/none", false), "HTTP 500");
        checkEq("M2 只有 BlockException 处理器", httpGet(http, base + "/mvc/block-only", true),
            "HTTP 429 BlockException 处理器(参数实际是 FlowException)");
        checkEq("M3 同一个 advice 里还有 Exception 处理器", httpGet(http, base + "/mvc/block-and-generic", true),
            "HTTP 500 Exception 处理器(参数实际是 UndeclaredThrowableException)");
        checkEq("M4 Exception 处理器在优先级更高的 advice", httpGet(http, base + "/mvc/generic-first", true),
            "HTTP 500 Exception 处理器(参数实际是 UndeclaredThrowableException)");
        checkEq("M5 BlockException 处理器在优先级更高的 advice", httpGet(http, base + "/mvc/block-first", true),
            "HTTP 429 BlockException 处理器(参数实际是 FlowException)");
    }

    /** 只返回状态码;withBody 为 true 时附上响应正文(M1 的正文是 Spring Boot 默认的错误 JSON,不比较)。 */
    private static String httpGet(HttpClient http, String url, boolean withBody) throws Exception {
        HttpRequest req = HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(5)).GET().build();
        HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString());
        return "HTTP " + resp.statusCode() + (withBody ? " " + resp.body() : "");
    }

    private void recordLog() throws IOException {
        section("八、上面这些找不到的 handler 留下了什么");
        Path dir = Path.of("target", "sentinel-logs");
        List<String> warns;
        try (Stream<Path> files = Files.list(dir)) {
            warns = files.filter(p -> p.getFileName().toString().startsWith("sentinel-record.log"))
                .flatMap(p -> {
                    try {
                        return Files.readAllLines(p).stream();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                })
                .filter(l -> l.contains("Cannot find"))
                .collect(Collectors.toList());
        }
        warns.forEach(l -> System.out.println("    " + l.substring(l.indexOf("Cannot find"))));
        // 真有问题的 12 行:S2 S3 S4 S6 S7 S9 的 blockHandler 各 1 行,F1、F3 的 fallback 各 2 行
        // (两种参数表各找一次),D2 的 defaultFallback 2 行。
        // 另外 9 行是正常配置留下的:带 Throwable 参数的 fallback / defaultFallback 会先按
        // 不带 Throwable 的参数表找一次,找不到也写一行(S9、F3、E、E4、B、N、P3、D1、D3 各 1 行)。
        checkEq("WARN 行数", String.valueOf(warns.size()), "21");
    }

    private void validator() {
        section("九、启动时校验能提前发现哪些");
        // 遍历容器里所有 bean,拿到代理背后的真实类再校验
        List<String> problems = new ArrayList<>();
        for (String name : ctx.getBeanDefinitionNames()) {
            problems.addAll(HandlerValidator.validate(AopUtils.getTargetClass(ctx.getBean(name))));
        }
        problems.forEach(p -> System.out.println("    " + p));
        checkEq("发现的问题数", String.valueOf(problems.size()), "11");
    }

    // ---------------------------------------------------------------- 工具

    private static ClusterNode node(String resource) {
        return ClusterBuilderSlot.getClusterNode(resource);
    }

    private static String outcome(Callable<?> call) {
        try {
            return "返回 " + call.call();
        } catch (Throwable t) {
            String s = "抛出 " + t.getClass().getSimpleName();
            if (t.getCause() != null && t.getCause() != t) {
                s += "(cause " + t.getCause().getClass().getSimpleName() + ")";
            }
            return s;
        }
    }

    private void section(String title) {
        System.out.println();
        System.out.println(title);
    }

    private void check(String label, Callable<?> call, String expected) {
        checkEq(label, outcome(call), expected);
    }

    private void checkList(String label, List<String> actual, List<String> expected) {
        System.out.println("  " + label);
        for (int i = 0; i < expected.size(); i++) {
            checkEq("    第 " + (i + 1) + " 次", i < actual.size() ? actual.get(i) : "(无)", expected.get(i));
        }
    }

    private void statEx(String label, String resource, long expected) {
        ClusterNode n = node(resource);
        checkEq(label, n == null ? "(无节点)" : "异常 " + n.totalException(), "异常 " + expected);
    }

    private void stat(String label, String resource, long pass, long block, long exception) {
        ClusterNode n = node(resource);
        String actual = n == null ? "(无节点)"
            : "通过 " + n.totalPass() + " / 拦截 " + n.blockRequest() + " / 异常 " + n.totalException();
        checkEq(label, actual, "通过 " + pass + " / 拦截 " + block + " / 异常 " + exception);
    }

    private void checkEq(String label, String actual, String expected) {
        boolean ok = Objects.equals(actual, expected);
        if (!ok) {
            failures++;
        }
        System.out.printf("  %-44s %s%s%n", label, actual, ok ? "" : "    <-- 期望 " + expected);
    }
}

HandlerValidator.java:

package demo;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 按 Sentinel 1.8.10 AbstractSentinelAspectSupport 的匹配规则,在启动时把每个
 * blockHandler / fallback / defaultFallback 解析一遍。Sentinel 自己要等到第一次
 * 被拦、第一次失败时才解析,找不到只在 sentinel-record.log 里写一行 WARN。
 */
public final class HandlerValidator {

    private HandlerValidator() {}

    public static List<String> validate(Class<?> type) {
        List<String> problems = new ArrayList<>();
        SentinelResource onClass = type.getAnnotation(SentinelResource.class);
        for (Method m : annotatedMethods(type)) {
            SentinelResource a = m.getAnnotation(SentinelResource.class);
            if (a == null) {
                continue;
            }
            String where = type.getSimpleName() + "#" + m.getName();
            Class<?>[] params = m.getParameterTypes();

            if (!a.blockHandler().isEmpty()) {
                boolean mustStatic = a.blockHandlerClass().length > 0;
                Class<?> location = mustStatic ? a.blockHandlerClass()[0] : type;
                if (find(location, a.blockHandler(), mustStatic, m.getReturnType(), append(params, BlockException.class)) == null) {
                    problems.add(where + ": blockHandler " + a.blockHandler() + " 不匹配,要求 "
                        + describe(mustStatic, m.getReturnType(), append(params, BlockException.class)));
                }
            }

            boolean fallbackFound = false;
            if (!a.fallback().isEmpty()) {
                boolean mustStatic = a.fallbackClass().length > 0;
                Class<?> location = mustStatic ? a.fallbackClass()[0] : type;
                fallbackFound = find(location, a.fallback(), mustStatic, m.getReturnType(), params) != null
                    || find(location, a.fallback(), mustStatic, m.getReturnType(), append(params, Throwable.class)) != null;
                if (!fallbackFound) {
                    problems.add(where + ": fallback " + a.fallback() + " 不匹配,要求 "
                        + describe(mustStatic, m.getReturnType(), params) + " 或 "
                        + describe(mustStatic, m.getReturnType(), append(params, Throwable.class)));
                }
            }

            // fallback 找不到时才会用 defaultFallback;方法上没写就看类上的
            String df = a.defaultFallback();
            Class<?>[] dfClass = a.fallbackClass();
            if (df.isEmpty() && onClass != null) {
                df = onClass.defaultFallback();
                if (dfClass.length == 0) {
                    dfClass = onClass.fallbackClass();
                }
            }
            if (!fallbackFound && !df.isEmpty()) {
                boolean mustStatic = dfClass.length > 0;
                Class<?> location = mustStatic ? dfClass[0] : type;
                if (find(location, df, mustStatic, m.getReturnType()) == null
                    && find(location, df, mustStatic, m.getReturnType(), Throwable.class) == null) {
                    problems.add(where + ": defaultFallback " + df + " 不匹配,要求 "
                        + describe(mustStatic, m.getReturnType()) + " 或 "
                        + describe(mustStatic, m.getReturnType(), Throwable.class));
                }
            }
        }
        problems.sort(null);
        return problems;
    }

    /** 切点按方法上的注解匹配,父类里声明的方法也会被拦,所以沿父类往上收集。 */
    private static List<Method> annotatedMethods(Class<?> type) {
        List<Method> out = new ArrayList<>();
        for (Class<?> c = type; c != null && c != Object.class; c = c.getSuperclass()) {
            for (Method m : c.getDeclaredMethods()) {
                if (m.isAnnotationPresent(SentinelResource.class)) {
                    out.add(m);
                }
            }
        }
        return out;
    }

    /** 和 Sentinel 的 findMethod 一样:当前类找不到就沿父类往上找,不看接口。 */
    private static Method find(Class<?> c, String name, boolean mustStatic, Class<?> returnType, Class<?>... params) {
        for (; c != null && c != Object.class; c = c.getSuperclass()) {
            for (Method m : c.getDeclaredMethods()) {
                if (m.getName().equals(name)
                    && (!mustStatic || Modifier.isStatic(m.getModifiers()))
                    && returnType.isAssignableFrom(m.getReturnType())
                    && Arrays.equals(params, m.getParameterTypes())) {
                    return m;
                }
            }
        }
        return null;
    }

    private static Class<?>[] append(Class<?>[] params, Class<?> last) {
        Class<?>[] out = Arrays.copyOf(params, params.length + 1);
        out[params.length] = last;
        return out;
    }

    private static String describe(boolean mustStatic, Class<?> ret, Class<?>... params) {
        return (mustStatic ? "static " : "") + ret.getSimpleName() + " ("
            + Arrays.stream(params).map(Class::getSimpleName).collect(Collectors.joining(", ")) + ")";
    }
}

Exceptions.java:

package demo;

/** 参数不合法:调用方的错,不是依赖的故障。 */
class BadRequestException extends RuntimeException {
    BadRequestException(String msg) { super(msg); }
}

/** BadRequestException 的子类,用来看 exceptionsToIgnore 是否按继承匹配。 */
class MissingParamException extends BadRequestException {
    MissingParamException(String msg) { super(msg); }
}

Handlers.java:

package demo;

import com.alibaba.csp.sentinel.slots.block.BlockException;

/** 放在别的类里的 blockHandler:通过 blockHandlerClass 引用。 */
public class Handlers {

    // 忘了写 static
    public String instanceHandler(String id, BlockException e) {
        return "blockHandler(" + e.getClass().getSimpleName() + ")";
    }

    public static String staticHandler(String id, BlockException e) {
        return "blockHandler(" + e.getClass().getSimpleName() + ")";
    }
}

SignatureService.java(实验一):

package demo;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import org.springframework.stereotype.Service;

/**
 * 每个方法对应一种 blockHandler / fallback 写法。
 * 带 sig. 前缀的资源都配了 count=0 的流控规则,每次调用都会被拦。
 */
@Service
public class SignatureService {

    // S1 正确写法:原参数 + BlockException,返回类型相同
    @SentinelResource(value = "sig.ok", blockHandler = "okBlocked")
    public String ok(String id) { return "biz:" + id; }

    public String okBlocked(String id, BlockException e) {
        return "blockHandler(" + e.getClass().getSimpleName() + ")";
    }

    // S2 最后一个参数写成 Exception
    @SentinelResource(value = "sig.exParam", blockHandler = "exParamBlocked")
    public String exParam(String id) { return "biz:" + id; }

    public String exParamBlocked(String id, Exception e) {
        return "blockHandler(" + e.getClass().getSimpleName() + ")";
    }

    // S3 最后一个参数写成 BlockException 的子类
    @SentinelResource(value = "sig.flowParam", blockHandler = "flowParamBlocked")
    public String flowParam(String id) { return "biz:" + id; }

    public String flowParamBlocked(String id, FlowException e) {
        return "blockHandler(" + e.getClass().getSimpleName() + ")";
    }

    // S4 原方法参数是 long,blockHandler 写成 Long
    @SentinelResource(value = "sig.boxedParam", blockHandler = "boxedParamBlocked")
    public String boxedParam(long id) { return "biz:" + id; }

    public String boxedParamBlocked(Long id, BlockException e) {
        return "blockHandler(" + e.getClass().getSimpleName() + ")";
    }

    // S5 返回类型可以更窄:原方法返回 CharSequence,blockHandler 返回 String
    @SentinelResource(value = "sig.narrowReturn", blockHandler = "narrowReturnBlocked")
    public CharSequence narrowReturn(String id) { return "biz:" + id; }

    public String narrowReturnBlocked(String id, BlockException e) {
        return "blockHandler(" + e.getClass().getSimpleName() + ")";
    }

    // S6 原方法返回 int,blockHandler 返回 Integer
    @SentinelResource(value = "sig.boxedReturn", blockHandler = "boxedReturnBlocked")
    public int boxedReturn(String id) { return 1; }

    public Integer boxedReturnBlocked(String id, BlockException e) { return -1; }

    // S7 blockHandlerClass 里的方法不是 static
    @SentinelResource(value = "sig.nonStatic", blockHandler = "instanceHandler", blockHandlerClass = Handlers.class)
    public String nonStatic(String id) { return "biz:" + id; }

    // S8 blockHandlerClass 里的 static 方法(对照)
    @SentinelResource(value = "sig.static", blockHandler = "staticHandler", blockHandlerClass = Handlers.class)
    public String staticOk(String id) { return "biz:" + id; }

    // S9 blockHandler 签名写错,但配了 fallback
    @SentinelResource(value = "sig.toFallback", blockHandler = "toFallbackBlocked", fallback = "toFallbackFallback")
    public String toFallback(String id) { return "biz:" + id; }

    public String toFallbackBlocked(String id, Exception e) {
        return "blockHandler(" + e.getClass().getSimpleName() + ")";
    }

    public String toFallbackFallback(String id, Throwable t) {
        return "fallback(" + t.getClass().getSimpleName() + ")";
    }

    // S10 private 的 blockHandler
    @SentinelResource(value = "sig.private", blockHandler = "privateBlocked")
    public String privateHandler(String id) { return "biz:" + id; }

    private String privateBlocked(String id, BlockException e) {
        return "blockHandler(" + e.getClass().getSimpleName() + ")";
    }

    // F1 fallback 的最后一个参数写成 Exception(没有流控规则,业务自己抛异常)
    @SentinelResource(value = "fb.exParam", fallback = "fbExParamFallback")
    public String fbExParam(String id) { throw new IllegalStateException("db down"); }

    public String fbExParamFallback(String id, Exception e) {
        return "fallback(" + e.getClass().getSimpleName() + ")";
    }

    // F2 fallback 只写原参数:能匹配上,但拿不到异常
    @SentinelResource(value = "fb.noEx", fallback = "fbNoExFallback")
    public String fbNoEx(String id) { throw new IllegalStateException("db down"); }

    public String fbNoExFallback(String id) { return "fallback(拿不到异常)"; }

    // F3 fallback 签名写错,同时配了 defaultFallback
    @SentinelResource(value = "fb.toDefault", fallback = "fbToDefaultFallback", defaultFallback = "fbDefault")
    public String fbToDefault(String id) { throw new IllegalStateException("db down"); }

    public String fbToDefaultFallback(String id, Exception e) {
        return "fallback(" + e.getClass().getSimpleName() + ")";
    }

    public String fbDefault(Throwable t) {
        return "defaultFallback(" + t.getClass().getSimpleName() + ")";
    }
}

ExceptionService.java(实验二):

package demo;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import java.io.IOException;
import java.io.UncheckedIOException;
import org.springframework.stereotype.Service;

/** 业务方法按参数抛出不同的异常,看切面怎么分流。这里没有任何流控规则。 */
@Service
public class ExceptionService {

    static RuntimeException runtime(String kind) {
        switch (kind) {
            case "bad": return new BadRequestException("id 为空");
            case "missing": return new MissingParamException("缺少 id");
            case "wrapped": return new IllegalStateException("包了一层", new BadRequestException("id 为空"));
            case "io": return new UncheckedIOException(new IOException("连接被重置"));
            default: return new IllegalStateException("数据库超时");
        }
    }

    static void fail(String kind) {
        if ("oom".equals(kind)) {
            throw new OutOfMemoryError("模拟:堆满了");
        }
        throw runtime(kind);
    }

    // E1 默认:exceptionsToTrace = {Throwable.class},exceptionsToIgnore 为空
    @SentinelResource(value = "ex.default", fallback = "fb")
    public String byDefault(String kind) { fail(kind); return "unreachable"; }

    // E2 忽略参数错误
    @SentinelResource(value = "ex.ignore", fallback = "fb", exceptionsToIgnore = BadRequestException.class)
    public String ignore(String kind) { fail(kind); return "unreachable"; }

    // E3 只追踪 IO 类异常
    @SentinelResource(value = "ex.traceIo", fallback = "fb", exceptionsToTrace = UncheckedIOException.class)
    public String traceIo(String kind) { fail(kind); return "unreachable"; }

    // E4 默认配置,但 fallback 遇到 Error 原样抛出
    @SentinelResource(value = "ex.rethrowError", fallback = "fbRethrowError")
    public String rethrowError(String kind) { fail(kind); return "unreachable"; }

    public String fbRethrowError(String kind, Throwable t) {
        if (t instanceof Error) {
            throw (Error) t;
        }
        return "fallback(" + t.getClass().getSimpleName() + ")";
    }

    public String fb(String kind, Throwable t) {
        return "fallback(" + t.getClass().getSimpleName() + ")";
    }
}

QueryService.java(实验三):

package demo;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;

/**
 * 两个一模一样的查询,唯一的区别是第二个把 BadRequestException 放进了 exceptionsToIgnore。
 * 两个资源都配了"异常数 > 2 就熔断 30 秒"的规则。
 */
@Service
public class QueryService {

    @SentinelResource(value = "query.default", blockHandler = "blocked", fallback = "fb")
    public String query(String id) {
        if (id.isEmpty()) {
            throw new BadRequestException("id 为空");
        }
        return "ok:" + id;
    }

    @SentinelResource(value = "query.ignore", blockHandler = "blocked", fallback = "fb",
        exceptionsToIgnore = BadRequestException.class)
    public String queryIgnoringBadRequest(String id) {
        if (id.isEmpty()) {
            throw new BadRequestException("id 为空");
        }
        return "ok:" + id;
    }

    public String blocked(String id, BlockException e) {
        return "blockHandler(" + e.getClass().getSimpleName() + ")";
    }

    public String fb(String id, Throwable t) {
        return "fallback(" + t.getClass().getSimpleName() + ")";
    }
}

InnerService.java 和 OuterService.java(实验四):

package demo;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;

/** 下游资源:配了 count=0 的规则,而且两个方法都没写 blockHandler/fallback。 */
@Service
public class InnerService {

    @SentinelResource("inner.declared")
    public String declared() throws BlockException { return "inner"; }

    @SentinelResource("inner.undeclared")
    public String undeclared() { return "inner"; }
}
package demo;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;

/** 上游资源:自己没有任何规则,调用 InnerService。 */
@Service
public class OuterService {

    private final InnerService inner;

    public OuterService(InnerService inner) { this.inner = inner; }

    @SentinelResource(value = "outer.declared", blockHandler = "blocked", fallback = "fb")
    public String callDeclared() throws BlockException { return inner.declared(); }

    @SentinelResource(value = "outer.undeclared", blockHandler = "blocked", fallback = "fb")
    public String callUndeclared() { return inner.undeclared(); }

    public String blocked(BlockException e) {
        // BlockException 带着触发它的规则,可以看出是谁被拦了
        return "outer.blockHandler(" + e.getClass().getSimpleName() + " 来自 " + e.getRule().getResource() + ")";
    }

    public String fb(Throwable t) {
        return "outer.fallback(" + t.getClass().getSimpleName() + ")";
    }
}

SelfCallService.java(实验五):

package demo;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;

@Service
public class SelfCallService {

    // 拿到的是容器里的代理对象,不是 this
    private final ObjectProvider<SelfCallService> self;

    public SelfCallService(ObjectProvider<SelfCallService> self) { this.self = self; }

    // 配了 count=0 的规则
    @SentinelResource(value = "self.target", blockHandler = "blocked")
    public String target() { return "biz"; }

    public String blocked(BlockException e) {
        return "blockHandler(" + e.getClass().getSimpleName() + ")";
    }

    public String viaThis() { return target(); }

    public String viaProxy() { return self.getObject().target(); }

    // fallback 自己也标了 @SentinelResource
    @SentinelResource(value = "self.failing", fallback = "annotatedFallback")
    public String failing() { throw new IllegalStateException("数据库超时"); }

    @SentinelResource("self.fallbackResource")
    public String annotatedFallback(Throwable t) { return "fallback"; }
}

ReportServiceA.java、ReportServiceB.java、ReportServiceC.java(实验六),A 和 B 只有类名和资源名不同:

package demo;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.stereotype.Service;

/** 类级别的 defaultFallback,两个方法返回类型不同。 */
@Service
@SentinelResource(defaultFallback = "df")
public class ReportServiceA {

    @SentinelResource("reportA.title")
    public String title() { throw new IllegalStateException("数据库超时"); }

    @SentinelResource("reportA.count")
    public Integer count() { throw new IllegalStateException("数据库超时"); }

    public String df(Throwable t) { return "defaultFallback"; }
}
package demo;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.stereotype.Service;

/** 类级别的 defaultFallback,两个方法返回类型不同。 */
@Service
@SentinelResource(defaultFallback = "df")
public class ReportServiceB {

    @SentinelResource("reportB.title")
    public String title() { throw new IllegalStateException("数据库超时"); }

    @SentinelResource("reportB.count")
    public Integer count() { throw new IllegalStateException("数据库超时"); }

    public String df(Throwable t) { return "defaultFallback"; }
}
package demo;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.stereotype.Service;

/** 两个参数相同、返回类型不同的方法共用一个同名 fallback。 */
@Service
public class ReportServiceC {

    @SentinelResource(value = "reportC.title", fallback = "fb")
    public String title(String id) { throw new IllegalStateException("数据库超时"); }

    @SentinelResource(value = "reportC.count", fallback = "fb")
    public Integer count(String id) { throw new IllegalStateException("数据库超时"); }

    public String fb(String id, Throwable t) { return "fallback"; }
}

MvcControllers.java(实验七):

package demo;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 实验九:五个接口都调用 SignatureService#exParam(blockHandler 签名写错,
 * 调用方拿到 UndeclaredThrowableException,cause 是 FlowException),
 * 区别只在各自生效的 @ExceptionHandler。每个 advice 用 assignableTypes 限定到一个接口。
 */
abstract class BaseController {
    private final SignatureService sig;
    BaseController(SignatureService sig) { this.sig = sig; }
    String call() { return sig.exParam("42"); }
}

@RestController
class NoAdviceController extends BaseController {
    NoAdviceController(SignatureService sig) { super(sig); }
    @GetMapping("/mvc/none") String get() { return call(); }
}

@RestController
class BlockOnlyController extends BaseController {
    BlockOnlyController(SignatureService sig) { super(sig); }
    @GetMapping("/mvc/block-only") String get() { return call(); }
}

@RestController
class BlockAndGenericController extends BaseController {
    BlockAndGenericController(SignatureService sig) { super(sig); }
    @GetMapping("/mvc/block-and-generic") String get() { return call(); }
}

@RestController
class GenericFirstController extends BaseController {
    GenericFirstController(SignatureService sig) { super(sig); }
    @GetMapping("/mvc/generic-first") String get() { return call(); }
}

@RestController
class BlockFirstController extends BaseController {
    BlockFirstController(SignatureService sig) { super(sig); }
    @GetMapping("/mvc/block-first") String get() { return call(); }
}

final class Responses {
    private Responses() {}

    static ResponseEntity<String> block(BlockException e) {
        return ResponseEntity.status(429).body("BlockException 处理器(参数实际是 " + e.getClass().getSimpleName() + ")");
    }

    static ResponseEntity<String> generic(Exception e) {
        return ResponseEntity.status(500).body("Exception 处理器(参数实际是 " + e.getClass().getSimpleName() + ")");
    }
}

// M2:只有 BlockException 处理器
@RestControllerAdvice(assignableTypes = BlockOnlyController.class)
class BlockOnlyAdvice {
    @ExceptionHandler(BlockException.class)
    ResponseEntity<String> onBlock(BlockException e) { return Responses.block(e); }
}

// M3:同一个 advice 里同时有 BlockException 和 Exception 处理器
@RestControllerAdvice(assignableTypes = BlockAndGenericController.class)
class BlockAndGenericAdvice {
    @ExceptionHandler(BlockException.class)
    ResponseEntity<String> onBlock(BlockException e) { return Responses.block(e); }

    @ExceptionHandler(Exception.class)
    ResponseEntity<String> onAny(Exception e) { return Responses.generic(e); }
}

// M4:两个 advice,Exception 处理器所在的优先级更高
@Order(1)
@RestControllerAdvice(assignableTypes = GenericFirstController.class)
class GenericFirstGenericAdvice {
    @ExceptionHandler(Exception.class)
    ResponseEntity<String> onAny(Exception e) { return Responses.generic(e); }
}

@Order(2)
@RestControllerAdvice(assignableTypes = GenericFirstController.class)
class GenericFirstBlockAdvice {
    @ExceptionHandler(BlockException.class)
    ResponseEntity<String> onBlock(BlockException e) { return Responses.block(e); }
}

// M5:两个 advice,BlockException 处理器所在的优先级更高
@Order(1)
@RestControllerAdvice(assignableTypes = BlockFirstController.class)
class BlockFirstBlockAdvice {
    @ExceptionHandler(BlockException.class)
    ResponseEntity<String> onBlock(BlockException e) { return Responses.block(e); }
}

@Order(2)
@RestControllerAdvice(assignableTypes = BlockFirstController.class)
class BlockFirstGenericAdvice {
    @ExceptionHandler(Exception.class)
    ResponseEntity<String> onAny(Exception e) { return Responses.generic(e); }
}

完整输出(运行两次,内容一致):

INFO: Sentinel log output type is: file
INFO: Sentinel log charset is: utf-8
INFO: Sentinel log base directory is: target/sentinel-logs/
INFO: Sentinel log name use pid is: false
INFO: Sentinel log level is: INFO

一、blockHandler / fallback 的签名(sig.* 每次都被流控拦下)
  S1 正确:(String, BlockException)               返回 blockHandler(FlowException)
  S2 末参数写成 Exception                           抛出 UndeclaredThrowableException(cause FlowException)
  S3 末参数写成 FlowException                       抛出 UndeclaredThrowableException(cause FlowException)
  S4 原参数 long,handler 写 Long                   抛出 UndeclaredThrowableException(cause FlowException)
  S5 原返回 CharSequence,handler 返回 String        返回 blockHandler(FlowException)
  S6 原返回 int,handler 返回 Integer                抛出 UndeclaredThrowableException(cause FlowException)
  S7 blockHandlerClass 里的实例方法                  抛出 UndeclaredThrowableException(cause FlowException)
  S8 blockHandlerClass 里的 static 方法            返回 blockHandler(FlowException)
  S9 blockHandler 写错,但有 fallback               返回 fallback(FlowException)
  S10 private 的 blockHandler                   返回 blockHandler(FlowException)
  F1 fallback 末参数写成 Exception                  抛出 IllegalStateException
  F2 fallback 只写原参数                            返回 fallback(拿不到异常)
  F3 fallback 写错,另有 defaultFallback            返回 defaultFallback(IllegalStateException)

二、哪些异常进 fallback、哪些算进统计(没有流控规则)
  E1 默认 + IllegalStateException                返回 fallback(IllegalStateException)
  E1 默认 + BadRequestException                  返回 fallback(BadRequestException)
  E1 默认 + OutOfMemoryError                     返回 fallback(OutOfMemoryError)
  E1 ex.default 记录的异常数                         异常 3
  E2 ignore + BadRequestException              抛出 BadRequestException
  E2 ignore + 子类 MissingParamException         抛出 MissingParamException
  E2 ignore + 被包了一层的 BadRequestException       返回 fallback(IllegalStateException)
  E2 ignore + IllegalStateException            返回 fallback(IllegalStateException)
  E2 ex.ignore 记录的异常数                          异常 2
  E3 traceIo + UncheckedIOException            返回 fallback(UncheckedIOException)
  E3 traceIo + IllegalStateException           抛出 IllegalStateException
  E3 ex.traceIo 记录的异常数                         异常 1
  E4 fallback 遇到 Error 原样抛出                    抛出 OutOfMemoryError
  E4 普通异常照常兜底                                  返回 fallback(IllegalStateException)
  E4 ex.rethrowError 记录的异常数                    异常 2

三、被 fallback 兜住的异常照样触发熔断(异常数 > 2 熔断 30 秒)
  B1 默认:5 次空 id,再 1 次正常 id
      第 1 次                                    返回 fallback(BadRequestException)
      第 2 次                                    返回 fallback(BadRequestException)
      第 3 次                                    返回 fallback(BadRequestException)
      第 4 次                                    返回 blockHandler(DegradeException)
      第 5 次                                    返回 blockHandler(DegradeException)
      第 6 次                                    返回 blockHandler(DegradeException)
  B2 忽略 BadRequestException:同样 6 次
      第 1 次                                    抛出 BadRequestException
      第 2 次                                    抛出 BadRequestException
      第 3 次                                    抛出 BadRequestException
      第 4 次                                    抛出 BadRequestException
      第 5 次                                    抛出 BadRequestException
      第 6 次                                    返回 ok:42

四、下游资源被拦,上游的 handler 被谁调用(只有 inner.* 有规则)
  N1 下游声明 throws BlockException                返回 outer.blockHandler(FlowException 来自 inner.declared)
  N1 outer.declared 通过/拦截/异常                   通过 1 / 拦截 0 / 异常 0
  N1 inner.declared 通过/拦截/异常                   通过 0 / 拦截 1 / 异常 0
  N2 下游没声明                                     返回 outer.fallback(UndeclaredThrowableException)
  N2 outer.undeclared 通过/拦截/异常                 通过 1 / 拦截 0 / 异常 1
  N2 inner.undeclared 通过/拦截/异常                 通过 0 / 拦截 1 / 异常 0

五、代理的边界(self.target 每次都被拦)
  P1 同类里 this.target()                         返回 biz
  P1 self.target 节点是否存在                        false
  P2 通过代理调用 target()                           返回 blockHandler(FlowException)
  P2 self.target 节点是否存在                        true
  P3 fallback 方法自己也标了 @SentinelResource        返回 fallback
  P3 self.fallbackResource 节点是否存在              false

六、类级 defaultFallback 的缓存只按名字(df 返回 String)
  D1 A 先调 title()(返回 String)                   返回 defaultFallback
  D1 A 再调 count()(返回 Integer)                  抛出 ClassCastException
  D2 B 先调 count()(返回 Integer)                  抛出 IllegalStateException
  D2 B 再调 title()(返回 String)                   抛出 IllegalStateException
  D3 C 先调 title(id)(返回 String)                 返回 fallback
  D3 C 再调 count(id)(返回 Integer)                抛出 ClassCastException

七、同一个异常到了 Spring MVC 的 @ExceptionHandler(sig.exParam 的 blockHandler 签名是错的)
  M1 没有任何 @ExceptionHandler                    HTTP 500
  M2 只有 BlockException 处理器                     HTTP 429 BlockException 处理器(参数实际是 FlowException)
  M3 同一个 advice 里还有 Exception 处理器              HTTP 500 Exception 处理器(参数实际是 UndeclaredThrowableException)
  M4 Exception 处理器在优先级更高的 advice               HTTP 500 Exception 处理器(参数实际是 UndeclaredThrowableException)
  M5 BlockException 处理器在优先级更高的 advice          HTTP 429 BlockException 处理器(参数实际是 FlowException)

八、上面这些找不到的 handler 留下了什么
    Cannot find method [exParamBlocked] in class [demo.SignatureService] with parameters [class java.lang.String, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find method [flowParamBlocked] in class [demo.SignatureService] with parameters [class java.lang.String, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find method [boxedParamBlocked] in class [demo.SignatureService] with parameters [long, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find method [boxedReturnBlocked] in class [demo.SignatureService] with parameters [class java.lang.String, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find static method [instanceHandler] in class [demo.Handlers] with parameters [class java.lang.String, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find method [toFallbackBlocked] in class [demo.SignatureService] with parameters [class java.lang.String, class com.alibaba.csp.sentinel.slots.block.BlockException]
    Cannot find method [toFallbackFallback] in class [demo.SignatureService] with parameters [class java.lang.String]
    Cannot find method [fbExParamFallback] in class [demo.SignatureService] with parameters [class java.lang.String]
    Cannot find method [fbExParamFallback] in class [demo.SignatureService] with parameters [class java.lang.String, class java.lang.Throwable]
    Cannot find method [fbToDefaultFallback] in class [demo.SignatureService] with parameters [class java.lang.String]
    Cannot find method [fbToDefaultFallback] in class [demo.SignatureService] with parameters [class java.lang.String, class java.lang.Throwable]
    Cannot find method [fbDefault] in class [demo.SignatureService] with parameters []
    Cannot find method [fb] in class [demo.ExceptionService] with parameters [class java.lang.String]
    Cannot find method [fbRethrowError] in class [demo.ExceptionService] with parameters [class java.lang.String]
    Cannot find method [fb] in class [demo.QueryService] with parameters [class java.lang.String]
    Cannot find method [fb] in class [demo.OuterService] with parameters []
    Cannot find method [annotatedFallback] in class [demo.SelfCallService] with parameters []
    Cannot find method [df] in class [demo.ReportServiceA] with parameters []
    Cannot find method [df] in class [demo.ReportServiceB] with parameters []
    Cannot find method [df] in class [demo.ReportServiceB] with parameters [class java.lang.Throwable]
    Cannot find method [fb] in class [demo.ReportServiceC] with parameters [class java.lang.String]
  WARN 行数                                      21

九、启动时校验能提前发现哪些
    ReportServiceA#count: defaultFallback df 不匹配,要求 Integer () 或 Integer (Throwable)
    ReportServiceB#count: defaultFallback df 不匹配,要求 Integer () 或 Integer (Throwable)
    ReportServiceC#count: fallback fb 不匹配,要求 Integer (String) 或 Integer (String, Throwable)
    SignatureService#boxedParam: blockHandler boxedParamBlocked 不匹配,要求 String (long, BlockException)
    SignatureService#boxedReturn: blockHandler boxedReturnBlocked 不匹配,要求 int (String, BlockException)
    SignatureService#exParam: blockHandler exParamBlocked 不匹配,要求 String (String, BlockException)
    SignatureService#fbExParam: fallback fbExParamFallback 不匹配,要求 String (String) 或 String (String, Throwable)
    SignatureService#fbToDefault: fallback fbToDefaultFallback 不匹配,要求 String (String) 或 String (String, Throwable)
    SignatureService#flowParam: blockHandler flowParamBlocked 不匹配,要求 String (String, BlockException)
    SignatureService#nonStatic: blockHandler instanceHandler 不匹配,要求 static String (String, BlockException)
    SignatureService#toFallback: blockHandler toFallbackBlocked 不匹配,要求 String (String, BlockException)
  发现的问题数                                       11

全部符合预期

小结

  • blockHandler、fallback、defaultFallback 都在第一次触发时按名字和参数表反射查找,参数逐个完全相同才算找到,找不到只在 sentinel-record.log 写一行 WARN,而这个文件里还混着正常配置留下的同样的 WARN。
  • blockHandler 的最后一个参数只能是 BlockException,fallback 额外的参数只能是 Throwable,基本类型和包装类型不通用,blockHandlerClass / fallbackClass 里只认 static。
  • 三级都找不到时 BlockException 原样抛出;它是受检异常,过代理就变成 UndeclaredThrowableException,Java 调用方的 catch (BlockException) 接不住。Spring MVC 的 @ExceptionHandler(BlockException.class) 能按 cause 匹配到它,但会输给同一个 advice 里的 Exception 处理器和优先级更高的 advice,而且 blockHandler 的降级逻辑照样没执行。
  • 默认连 Error 也进 fallback;fallback 兜住的异常照样计入熔断。“调用方的错”放进 exceptionsToIgnore,它按继承匹配,但不看 cause。
  • 切面的 catch (BlockException) 同时包住了业务方法:下游的限流会触发上游的 blockHandler,或者被上游记成异常。每个资源配自己的 handler。
  • 同类调用不经过代理,资源根本不存在;handler 也是在原始对象上反射调用的,标在它上面的注解都不生效。
  • defaultFallback 的缓存键里没有返回类型,返回类型不同的方法共用一个时,行为取决于谁先失败。
  • 签名问题可以在启动时按同样的规则提前检查出来。
— 文章结束 —返回文章归档 ↑

讨论

点击后加载 giscus 讨论。登录与发表由你自行操作。