← 全部文章ENGINEERING NOTES

Sentinel 链路限流为什么不生效:所有 Web 请求都在同一个 context 里

本文目录
  1. 链路模式比较的是 context 名,不是调用路径
  2. Web 适配器默认给所有请求同一个名字
  3. 为什么默认是 true
  4. 关掉开关的代价
  5. 内存:每个多出来的节点稳态约 15 KB
  6. 上限:context 用满之后,新入口上的规则不再检查
  7. 不受影响的部分
  8. 关掉之后,refResource 该写什么
  9. 关掉之后还会踩的坑
  10. refResource 写中间资源没用
  11. 在请求里手动 ContextUtil.enter 没用
  12. 换了线程就丢 context
  13. 每个入口一份配额
  14. 不想全局关掉的话
  15. 完整示例
  16. Web 实验
  17. 内存粗测
  18. 小结

一个 Spring MVC 应用,/a 和 /b 两个接口都调同一个方法 queryUser,这个方法用 @SentinelResource 标成了资源。需求很常见:/a 给后台批量任务用,要单独限住;/b 是用户请求,不受影响。Sentinel 的流控规则正好有一个“链路”模式:

FlowRule rule = new FlowRule("queryUser");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(2);
rule.setStrategy(RuleConstant.STRATEGY_CHAIN);
rule.setRefResource("/a");   // 只限从 /a 进来的 queryUser

规则加上,控制台里也看得到。在同一秒里连续请求 /a 十次,十次全过。没有报错,没有日志,规则就像不存在。

把 Spring Cloud Alibaba 的 spring.cloud.sentinel.web-context-unify 改成 false(直接用 Sentinel 的 Spring MVC 适配器时,是 SentinelWebMvcConfig#setWebContextUnify(false)),同一条规则下 /a 十次过 2 次,/b 十次全过。

这篇把这件事讲透:链路模式到底在比较什么,Web 适配器为什么默认让它失效,关掉开关要付出什么(实测的内存,以及 context 数量上限带来的故障模式),关掉之后还会踩哪些坑,不想全局关掉时有什么别的办法。源码和实验都基于 Sentinel 1.8.10(写这篇时 Maven Central 上最新的稳定版),Web 层用 Spring Boot 4.2.0 加 sentinel-spring-webmvc-v6x-adapter。

总览那篇提过一句:NodeSelectorSlot 按“资源 × Context 名”建 DefaultNode,链路限流用的就是它。这篇从这句话往下挖。

链路模式比较的是 context 名,不是调用路径

流控检查时,FlowRuleChecker 先要决定拿哪个节点的统计去和阈值比。链路模式走的是这一段(FlowRuleChecker#selectReferenceNode):

if (strategy == RuleConstant.STRATEGY_CHAIN) {
    if (!refResource.equals(context.getName())) {
        return null;
    }
    return node;
}

对不上时返回 null,上一层的处理是:

private static boolean passLocalCheck(FlowRule rule, Context context, DefaultNode node, int acquireCount,
                                      boolean prioritized) {
    Node selectedNode = selectNodeByRequesterAndStrategy(rule, context, node);
    if (selectedNode == null) {
        return true;
    }
    return rule.getRater().canPass(selectedNode, acquireCount, prioritized);
}

这里说的是本地流控,也就是规则 clusterMode=false(默认值)时走的路径;canPassCheck 在 clusterMode=true 时走的是 passClusterCheck,集群流控的语义另当别论,不在这篇的范围里。在本地流控下,这两段决定了链路模式的脾气:

  1. refResource 只和当前线程 Context 的名字做 equals。它不看调用栈里的上一级资源是谁,也不看中间经过了什么。控制台把这个字段叫“入口资源”,准确的说法是:它必须是某个 context 的名字。
  2. 对不上就放行。名字写错、context 不对、配置不生效,表现都一样:规则像不存在,没有任何提示。

对上了,拿来比的 node 是这个资源在这个 context 下的 DefaultNode。NodeSelectorSlot 用 context 名当 key:

DefaultNode node = map.get(context.getName());
if (node == null) {
    synchronized (this) {
        node = map.get(context.getName());
        if (node == null) {
            node = new DefaultNode(resourceWrapper, null);
            // ... copy-on-write 放进 map
            // Build invocation tree
            ((DefaultNode) context.getLastNode()).addChild(node);
        }
    }
}

同一个资源在几个 context 里被调用,就有几个 DefaultNode,各记各的;它们再共享同一个 ClusterNode,直接模式(STRATEGY_DIRECT)用的是那个汇总。

context 名由谁定?由线程里第一个 ContextUtil.enter(name, origin) 定。ContextUtil#trueEnter 开头就是:

Context context = contextHolder.get();
if (context == null) {
    // 找或建 EntranceNode,new Context(node, name),放进 ThreadLocal
}
return context;

线程里已经有 context 时,再 enter 什么名字都原样返回旧的。Web 请求里第一个 enter 的,是 Web 适配器。

Web 适配器默认给所有请求同一个名字

Spring MVC 适配器的拦截器在 preHandle 里做的是(AbstractSentinelInterceptor):

String origin = parseOrigin(request);
String contextName = getContextName(request);
ContextUtil.enter(contextName, origin);
Entry entry = SphU.entry(resourceName, ResourceTypeConstants.COMMON_WEB, EntryType.IN);

SentinelWebInterceptor#getContextName:

if (config.isWebContextUnify()) {
    return super.getContextName(request);   // 固定返回 "sentinel_spring_web_context"
}
return getResourceName(request);

SentinelWebMvcConfig 里 webContextUnify 默认是 true。于是所有接口都在名叫 sentinel_spring_web_context 的 context 里,refResource = "/a" 永远等于不了它。Spring Cloud Alibaba(看的是 2025.1.0.0)的 SentinelProperties 里也是 webContextUnify = true,原样传给这个配置。

各类入口的 context 名(1.8.10 源码):

入口 context 名 怎么按入口区分
Servlet CommonFilter(javax) sentinel_web_servlet_context init-param WEB_CONTEXT_UNIFY=false,改用 URL
Spring MVC 拦截器(webmvc、webmvc-v6x) sentinel_spring_web_context setWebContextUnify(false),改用 Web 资源名
Spring WebFlux SentinelWebFluxFilter sentinel_spring_webflux_context 没有开关,继承后覆盖 getContextName
Spring Cloud Gateway sentinel_gateway_context$$route$$ 加路由 ID 本来就按路由分
Dubbo 提供端 方法资源名 本来就按方法分
没人 enter 过的线程(MQ 监听、定时任务、线程池) sentinel_default_context 自己 ContextUtil.enter

示例应用(完整代码在文末)有七个接口,除了 /a、/b,还有几个后面要用的:/c 经过一个中间资源 viaWrapper 再调 queryUser;/manual 在方法里先 ContextUtil.enter("manual_entry");/async 把 queryUser 扔到 CompletableFuture.supplyAsync 里;/async-fix 是它的修正版;/users/{id} 带路径变量。默认配置下先不加规则,把每个接口走 20 遍,打印 Constants.ROOT 往下的调用树:

machine-root
  sentinel_spring_web_context
    /manual
    /b
    /async-fix
    /users/{id}
    /async
    /c
      viaWrapper
    /a
      queryUser
  sentinel_default_context
    queryUser

注意 queryUser 只挂在 /a 下面。/b、/c、/manual、/users/{id} 都调过它,可同一个 context 里它只有一个 DefaultNode,而 addChild 只在新建节点时调一次,挂在第一次走到它的那个父节点下(子节点用 HashSet 存,打印顺序每次运行可能不同,谁先被调用谁就是那个父节点)。控制台“簇点链路”画的就是这棵树,看上去像“只有 /a 调了 queryUser”,实际上所有入口的调用都记在这一个节点上。/async 那一次调用则跑去了 sentinel_default_context,后面细说。

在这个状态下,链路规则能命中的入口只有 sentinel_spring_web_context 本身。下面每一格都是在一个新的整秒里连续请求 10 次、返回 OK 的次数,其余都是 BLOCKED(任何别的响应都会让实验报错退出,见文末说明),规则都是 queryUser 的 QPS 阈值 2:

规则:queryUser 的 QPS 阈值 2,每格是连续请求 10 次里 OK 的次数(10 = 没被限),其余都是 BLOCKED;带 * 的格子跨过了整秒,不作数
strategy / refResource                     /a         /b         /c    /manual     /async /async-fix   /users/7
DIRECT (control)                            2          2          2          2          2          2          2
CHAIN /a                                   10         10         10         10         10         10         10
CHAIN GET:/a                               10         10         10         10         10         10         10
CHAIN /async-fix                           10         10         10         10         10         10         10
CHAIN /users/{id}                          10         10         10         10         10         10         10
CHAIN viaWrapper                           10         10         10         10         10         10         10
CHAIN manual_entry                         10         10         10         10         10         10         10
CHAIN sentinel_spring_web_context           2          2          2          2         10          2          2
CHAIN sentinel_default_context             10         10         10         10          2         10         10

CHAIN sentinel_spring_web_context,同一秒内先 /a 后 /b:/a OK 2 次,/b OK 0 次
  • CHAIN /a、CHAIN GET:/a、CHAIN /users/{id} 整行是 10,对谁都不生效。
  • CHAIN sentinel_spring_web_context 对除 /async 以外的接口都生效,而且是合在一起限的:同一秒先打 /a 再打 /b,/a 过 2 次,/b 一次都没过。这已经等于一条直接模式规则,还漏掉了异步线程里的调用。

为什么默认是 true

不是一开始就这样。翻 Git 历史:

  • 1.6.2 及以前,Servlet 过滤器用 URL 当 context 名(ContextUtil.enter(target, origin)),链路模式开箱即用。
  • 1.6.3 改成统一的 sentinel_web_servlet_context(提交 #944,2019 年 7 月)。
  • 1.7.0 给 CommonFilter 加回 WEB_CONTEXT_UNIFY 参数,默认 true(#1111)。
  • Spring MVC 适配器的 web-context-unify 是 1.7.2 才有的,提交标题直接写着 “to support chain relation flow strategy”(#1328,2020 年 3 月)。

CommonFilter 里这个常量的注释给了理由:

If enabled, use the default context name, or else use the URL path as the context name … Please pay attention to the number of context (EntranceNode), which may affect the memory footprint.

每个 context 对应一个 EntranceNode,它下面每走到一个资源,就多一个 DefaultNode。统一成一个 context,下游资源不管被多少入口调用,都只有一个 DefaultNode;按入口拆开,节点数变成“入口数 × 每个入口走到的资源数”。默认值选的是省内存,代价是链路模式默认不可用。下面量一下这个内存到底多大。

关掉开关的代价

内存:每个多出来的节点稳态约 15 KB

NodeCost.java(文末)只用 sentinel-core,模拟 1000 个接口,每个接口都调同样 5 个下游资源,每秒每个接口调一次,跑完 GC 三次后读堆占用。两种配置各跑一次 5 秒、两次 65 秒:

context 数 5 秒后堆占用 65 秒后堆占用(两次)
unify=true 2 12.4 MB 41.6 MB / 41.6 MB
unify=false 1001 25.9 MB 132.3 MB / 131.1 MB

关掉之后多出约 6000 个节点(1000 个 EntranceNode,5000 个下游资源的 DefaultNode,减去原来共享的 5 个),65 秒时多了 90 MB 左右,平均每个节点约 15 KB。环境是 OpenJDK 21.0.13、SerialGC、4 核 Xeon 2.30GHz,堆占用取的是 MemoryMXBean 在三次 System.gc() 之后的读数,属于粗测,看量级即可。

5 秒和 65 秒差这么多,是因为节点的统计窗口是用到才建的。DefaultNode 继承自 StatisticNode,带两套滑动窗口:秒级 2 个桶,分钟级 60 个桶(LeapArray 在总览里讲过)。数组一开始就分配好,但桶对象要等流量落到对应的时间段才创建,持续有流量一分钟后 60 个分钟桶才全部建出来,之后循环复用、不再增长。每个桶里是一组 LongAdder 计数器。所以 15 KB 是“每秒都有流量”时的稳态,冷门入口要小得多。

拿来估算:一个有 200 个接口、每个接口平均经过 10 个 Sentinel 资源的应用,关掉 unify 大约多出 2200 个节点,稳态 30 多 MB。不算小,但多数服务吃得下。更值得防的是下面这个上限。

上限:context 用满之后,新入口上的规则不再检查

ContextUtil#trueEnter 里新建 context 前有一道检查:

if (localCacheNameMap.size() > Constants.MAX_CONTEXT_NAME_SIZE) {   // 2000
    setNullContext();
    return NULL_CONTEXT;
}

CtSph#entryWithPriority 一开头:

Context context = ContextUtil.getContext();
if (context instanceof NullContext) {
    // The {@link NullContext} indicates that the amount of context has exceeded the threshold,
    // so here init the entry only. No rule checking will be done.
    return new CtEntry(resourceWrapper, null, context);
}

从这两段可以读出故障时的表现:

  • 已有的 context 不受影响。 它们的 EntranceNode 已经在 map 里,trueEnter 直接取到,这些入口上的规则照常检查。
  • 新名字拿到 NullContext。 它被放进线程,这个请求后面每一次 SphU.entry 都走上面那条分支。受影响的不只是链路规则,而是这个请求经过的所有资源上的所有规则:直接模式限流、熔断、热点参数、系统保护都跳过,也不计数。
  • 几乎没有提示。 整个进程只会在 Sentinel 的记录日志(默认 ~/logs/csp/sentinel-record.log.*)里打一行 WARN,之后不再重复:
WARNING [SentinelStatusChecker] WARN: Amount of context exceeds the threshold 2000. Entries in new contexts will NOT take effect!
  • map 里一开始就有 sentinel_default_context,所以留给业务入口的名字是 2000 个。

Spring MVC 拦截器拿的是匹配到的路径模式(/users/{id}),关掉 unify 后 context 数就是接口数(开了 httpMethodSpecify 再乘以方法数),一般离 2000 很远。风险在名字没有上界的入口:拿 URL 原文当名字的(CommonFilter 关了 WEB_CONTEXT_UNIFY 又没配 UrlCleaner,/order/1、/order/2 各算一个),或者手动 enter 时把用户 ID、订单号、请求参数拼进了名字。

防守上做三件事:

  1. 命名有界。 context 名只能来自一个有限集合:路径模式;UrlCleaner 把变量段归一(/order/123 变成 /order/{id}),不认识的 URL 归到一个固定名字或直接排除;手动 enter 只用常量字符串。
  2. 监控和告警。 采集上面那行 WARN 的关键字;或者在应用里定时读 ContextUtil.contextSize() 上报成指标,离 2000 还远的时候就报警,而不是等到用满。
  3. 入口限流不要只有这一层。 应用内的 Sentinel 规则依赖 context,出了这种故障会整体失效。网关、负载均衡或 Ingress 上按来源、按路由的限流不依赖应用内的 context,可以兜底。

另外,名字无界的入口即使开着 unify 也有同类问题:URL 原文同时也是资源名,资源数超过 MAX_SLOT_CHAIN_SIZE(6000)之后新资源同样不做检查。关掉 unify 只是让 context 的上限更早到来,UrlCleaner 两边都要配。

不受影响的部分

直接模式和关联模式用的是 ClusterNode;熔断、热点参数、系统保护规则也都不看 context 名。所以在 context 数没到上限的正常路径上,关掉 unify 不改变这些规则的行为,实验里 DIRECT (control) 一行在三组配置下都是 2。按来源(limitApp)限流看的是 origin,也与此无关。控制台“簇点链路”会变成每个接口一棵子树。

关掉之后,refResource 该写什么

关掉 unify 再跑一遍:

machine-root
  /async
    /async
  /c
    /c
      viaWrapper
        queryUser
  /async-fix
    queryUser
    /async-fix
  /users/{id}
    /users/{id}
      queryUser
  /manual
    /manual
      queryUser
  /b
    /b
      queryUser
  /a
    /a
      queryUser
  sentinel_default_context
    queryUser

每个接口都成了一个入口。EntranceNode 的名字和 Web 资源名相同,所以看到 /a 下面又是 /a:外层是入口,内层是拦截器建的 Web 资源。表格:

规则:queryUser 的 QPS 阈值 2,每格是连续请求 10 次里 OK 的次数(10 = 没被限),其余都是 BLOCKED;带 * 的格子跨过了整秒,不作数
strategy / refResource                     /a         /b         /c    /manual     /async /async-fix   /users/7
DIRECT (control)                            2          2          2          2          2          2          2
CHAIN /a                                    2         10         10         10         10         10         10
CHAIN GET:/a                               10         10         10         10         10         10         10
CHAIN /async-fix                           10         10         10         10         10          2         10
CHAIN /users/{id}                          10         10         10         10         10         10          2
CHAIN viaWrapper                           10         10         10         10         10         10         10
CHAIN manual_entry                         10         10         10         10         10         10         10
CHAIN sentinel_spring_web_context          10         10         10         10         10         10         10
CHAIN sentinel_default_context             10         10         10         10          2         10         10

CHAIN sentinel_spring_web_context,同一秒内先 /a 后 /b:/a OK 10 次,/b OK 10 次

CHAIN /a 只限 /a,CHAIN /users/{id} 只限 /users/7,其他接口不受影响,这才是想要的效果。

refResource 必须逐字等于 context 名。Spring MVC 适配器关掉 unify 后,context 名就是 getResourceName(request) 的返回值,它依次做了这些变换:

  1. 取 HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE,也就是路径模式 /users/{id},不是 /users/7。
  2. 过一遍 UrlCleaner(如果配了)。
  3. contextPathSpecify 为 true 时(这是默认值),前面拼上 context path。应用配了 server.servlet.context-path=/api,名字就是 /api/a。
  4. httpMethodSpecify 为 true 时,前面拼上 GET: 这样的方法前缀。

第三组实验打开了 httpMethodSpecify(Spring Cloud Alibaba 里是 spring.cloud.sentinel.http-method-specify):

规则:queryUser 的 QPS 阈值 2,每格是连续请求 10 次里 OK 的次数(10 = 没被限),其余都是 BLOCKED;带 * 的格子跨过了整秒,不作数
strategy / refResource                     /a         /b         /c    /manual     /async /async-fix   /users/7
DIRECT (control)                            2          2          2          2          2          2          2
CHAIN /a                                   10         10         10         10         10         10         10
CHAIN GET:/a                                2         10         10         10         10         10         10
CHAIN /async-fix                           10         10         10         10         10         10         10
CHAIN /users/{id}                          10         10         10         10         10         10         10
CHAIN viaWrapper                           10         10         10         10         10         10         10
CHAIN manual_entry                         10         10         10         10         10         10         10
CHAIN sentinel_spring_web_context          10         10         10         10         10         10         10
CHAIN sentinel_default_context             10         10         10         10          2         10         10

CHAIN sentinel_spring_web_context,同一秒内先 /a 后 /b:/a OK 10 次,/b OK 10 次

CHAIN /a 又失效了,换成 CHAIN GET:/a 才生效;CHAIN /async-fix 也失效了,因为它的 context 名变成了 GET:/async-fix。最稳的做法是到控制台的簇点链路里看入口节点的名字(或者调客户端的 tree 命令),原样复制,不要凭 URL 手写。

关掉之后还会踩的坑

refResource 写中间资源没用

/c 先进 viaWrapper,再调 queryUser。想限“经过 viaWrapper 的 queryUser”,写了 refResource = "viaWrapper",三组实验都是整行 10。链路模式只认 context 名,调用路径上的中间资源不算数。

要区分这种调用,只能把资源拆开:在 viaWrapper 里调一个叫 queryUser@wrapper 之类的资源。代价是这部分调用不再计入 queryUser 的 ClusterNode,queryUser 上的直接模式规则和熔断都看不到它们。

在请求里手动 ContextUtil.enter 没用

/manual 在方法里先 ContextUtil.enter("manual_entry") 再调 queryUser。CHAIN manual_entry 三组都是 10,调用树里也没有这个入口。原因就是前面那段 trueEnter:拦截器已经 enter 过,线程里有 context,这一行直接返回旧的。

手动 enter 只在本来没有 context 的线程里有用,比如 MQ 监听、定时任务的入口,而且要和 ContextUtil.exit() 成对,否则这个 context 会一直留在线程池的线程里,被下一个任务捡到。

换了线程就丢 context

/async 用 CompletableFuture.supplyAsync 在 ForkJoin 线程里调 queryUser。context 存在 ThreadLocal 里,新线程里没有,CtSph 就给它进了 sentinel_default_context。表里 /async 那一列,只有 CHAIN sentinel_default_context 能限住它,unify 开不开都一样。后果有两个:按入口写的链路规则管不到它;所有入口的异步调用,加上 MQ 监听和定时任务,全挤在 sentinel_default_context 下同一个 DefaultNode 里,一条规则会把它们一起限。

修法是 /async-fix:在请求线程里取出 context 的名字和 origin,到新线程里用同样的名字重新 enter,用完 exit。

Context current = ContextUtil.getContext();
String name = current.getName();
String origin = current.getOrigin();
return CompletableFuture.supplyAsync(() -> {
    ContextUtil.enter(name, origin);
    try {
        return userService.queryUser("1");
    } finally {
        ContextUtil.exit();
    }
}).join();

新线程里的 context 从 EntranceNode 开始,没有 Web 资源那一层,所以调用树里 queryUser 直接挂在入口 /async-fix 下面,和 Web 资源 /async-fix 是兄弟节点。但 context 名一样,NodeSelectorSlot 拿到的是同一个 DefaultNode,CHAIN /async-fix 就生效了。

不要图省事把请求线程的 Context 对象本身交给新线程(例如 ContextUtil.runOnContext(current, ...))。Context 里记着当前 entry:CtEntry 创建时把 context.getCurEntry() 设成自己的 parent,再把 curEntry 改成自己;退出时检查 curEntry 是不是自己,不是就把整条链清掉并抛 ErrorEntryFreeException。两个线程同时往同一个 Context 上挂 entry,这条链必然错乱。这一点是从源码推出来的,示例里没有去复现。

每个入口一份配额

链路规则计数在每个入口自己的 DefaultNode 上。给 /a 配 QPS 2 只管 /a;/a、/b 加起来要有个总上限,就再配一条直接模式规则,同一资源上的多条规则都会检查,哪条不过就拦。一条规则也只能写一个 refResource,三个入口各要限,就写三条。

不想全局关掉的话

unify 是全局开关:为了给一两个入口加链路规则,所有接口都要多出一套节点。有时候别的办法更合适:

  • 其实是想按调用方区分:用来源(origin)。实现 RequestOriginParser 给每个请求定一个调用方名,规则的 limitApp 写这个名字。来源是 ContextUtil.enter(name, origin) 的第二个参数,和 context 名无关,unify 开着也生效:selectNodeByRequesterAndStrategy 在 limitApp.equals(origin) 时,直接模式用的是 context.getOriginNode(),即这个资源下这个来源的统计。
    • 来源必须是可信的值:取已经认证过的身份(比如 mTLS 证书或已校验的 token 里的应用标识),或者由受信网关先删掉客户端带来的同名字段、再写入的内部标识。不能直接读一个客户端能随便填的请求头,否则调用方换个名字就能绕开针对自己的规则,还能冒充别人去耗别人的配额。
    • 解析不出来的请求要有明确去处。limitApp = other 的规则管不到空来源(FlowRuleManager.isOtherOrigin 对空字符串直接返回 false),所以让解析器对未知调用方返回一个固定值,比如 unknown,再给它配规则;同时保留一条 limitApp = default 的规则做总量上限,它对所有来源都生效。
    • 来源只是限流用的标签,不能代替鉴权。
  • 只有一两个入口要单独限:让这个入口调一个不同名字的资源,比如 queryUser:batch。意图明确,不多建节点。代价和前面拆 viaWrapper 一样:这部分调用不进 queryUser 的 ClusterNode。
  • 入口本来就不是 Web:MQ 监听、定时任务在自己的入口处 ContextUtil.enter("mq:order-created")(记得 exit),本来就不受 unify 影响,链路规则写这个名字即可。

真要关,就关,同时确认两件事:所有 Web 入口用的都是路径模式或配了 UrlCleaner,context 数离 2000 远;按“入口数 × 每个入口的资源数 × 15 KB”估一下稳态内存。

完整示例

两部分:一个 Spring Boot 应用跑三组 Web 实验,一个单文件程序(只依赖 sentinel-core)粗测内存。需要 JDK 17 及以上和 Maven,第一次运行要从 Maven Central 下载依赖。我跑的是 OpenJDK 21.0.13、Maven 3.9.11、Spring Boot 4.2.0、Sentinel 1.8.10,Linux x86_64。

Web 实验

目录结构:

chain-demo/
├── pom.xml
├── run.sh
└── src/main/java/demo/
    ├── ChainDemoApplication.java
    ├── DemoController.java
    ├── Experiments.java
    ├── UserService.java
    └── Wrapper.java

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-chain-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-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aspectj</artifactId>
    </dependency>
    <dependency>
      <groupId>com.alibaba.csp</groupId>
      <artifactId>sentinel-spring-webmvc-v6x-adapter</artifactId>
      <version>${sentinel.version}</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba.csp</groupId>
      <artifactId>sentinel-annotation-aspectj</artifactId>
      <version>${sentinel.version}</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>chain-demo</finalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

ChainDemoApplication.java,两个开关对应 Spring Cloud Alibaba 的两个配置项:

package demo;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.SentinelWebInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.config.SentinelWebMvcConfig;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class ChainDemoApplication implements WebMvcConfigurer {

    // 这两个开关就是 Spring Cloud Alibaba 里的
    // spring.cloud.sentinel.web-context-unify 和 spring.cloud.sentinel.http-method-specify
    @Value("${demo.unify:true}")
    private boolean unify;

    @Value("${demo.method-prefix:false}")
    private boolean methodPrefix;

    public static void main(String[] args) {
        // Sentinel 默认把日志写到 ~/logs/csp,这里改到当前目录,跑完删掉即可
        System.setProperty("csp.sentinel.log.dir", "target/sentinel-logs");
        SpringApplication.run(ChainDemoApplication.class, args);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        SentinelWebMvcConfig config = new SentinelWebMvcConfig();
        config.setWebContextUnify(unify);
        config.setHttpMethodSpecify(methodPrefix);
        registry.addInterceptor(new SentinelWebInterceptor(config)).addPathPatterns("/**");
        System.out.printf("webContextUnify=%s, httpMethodSpecify=%s%n", unify, methodPrefix);
    }

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
}

UserService.java:

package demo;

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

@Service
public class UserService {

    // 被多个入口共用的下游资源:链路规则就是想区分"从哪个入口进来的 queryUser"
    @SentinelResource(value = "queryUser", blockHandler = "queryUserBlocked")
    public String queryUser(String id) {
        return "OK";
    }

    public String queryUserBlocked(String id, BlockException e) {
        return "BLOCKED";
    }
}

Wrapper.java:

package demo;

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

@Service
public class Wrapper {

    private final UserService userService;

    public Wrapper(UserService userService) {
        this.userService = userService;
    }

    // 一个中间层资源:/c -> viaWrapper -> queryUser
    @SentinelResource("viaWrapper")
    public String call(String id) {
        return userService.queryUser(id);
    }
}

DemoController.java:

package demo;

import com.alibaba.csp.sentinel.context.Context;
import com.alibaba.csp.sentinel.context.ContextUtil;
import java.util.concurrent.CompletableFuture;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    private final UserService userService;
    private final Wrapper wrapper;

    public DemoController(UserService userService, Wrapper wrapper) {
        this.userService = userService;
        this.wrapper = wrapper;
    }

    @GetMapping("/a")
    public String a() {
        return userService.queryUser("1");
    }

    @GetMapping("/b")
    public String b() {
        return userService.queryUser("1");
    }

    // 经过一个中间资源再调 queryUser
    @GetMapping("/c")
    public String c() {
        return wrapper.call("1");
    }

    // 带路径变量:拦截器用的是匹配到的模式 /users/{id},不是实际 URL
    @GetMapping("/users/{id}")
    public String user(@PathVariable String id) {
        return userService.queryUser(id);
    }

    // 在请求里"手动指定入口":拦截器已经进过 context,这一行什么都不做
    @GetMapping("/manual")
    public String manual() {
        ContextUtil.enter("manual_entry");
        return userService.queryUser("1");
    }

    // 换到别的线程执行:ThreadLocal 里的 context 带不过去
    @GetMapping("/async")
    public String asyncLost() {
        return CompletableFuture.supplyAsync(() -> userService.queryUser("1")).join();
    }

    // 修法:在新线程里用同一个名字重新进一次 context(不要把 Context 对象本身传过去)
    @GetMapping("/async-fix")
    public String asyncFix() {
        Context current = ContextUtil.getContext();
        String name = current.getName();
        String origin = current.getOrigin();
        return CompletableFuture.supplyAsync(() -> {
            ContextUtil.enter(name, origin);
            try {
                return userService.queryUser("1");
            } finally {
                ContextUtil.exit();
            }
        }).join();
    }
}

Experiments.java,应用启动后自己发请求、换规则、打印结果,然后退出:

package demo;

import com.alibaba.csp.sentinel.Constants;
import com.alibaba.csp.sentinel.node.Node;
import com.alibaba.csp.sentinel.node.DefaultNode;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
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.util.List;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class Experiments implements ApplicationRunner {

    static final List<String> PATHS = List.of("/a", "/b", "/c", "/manual", "/async", "/async-fix", "/users/7");
    static final List<String> REFS = List.of(
            "/a", "GET:/a", "/async-fix", "/users/{id}", "viaWrapper", "manual_entry",
            "sentinel_spring_web_context", "sentinel_default_context");
    static final int BURST = 10;
    static final double QPS = 2;

    private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
    private final Environment env;
    private final ApplicationContext ctx;
    private String base;

    public Experiments(Environment env, ApplicationContext ctx) {
        this.env = env;
        this.ctx = ctx;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        base = "http://127.0.0.1:" + env.getProperty("local.server.port");

        // 先不加规则把每个接口走一遍:建好节点,也让 JIT 热起来
        for (int i = 0; i < 20; i++) {
            for (String p : PATHS) {
                get(p);
            }
        }
        printTree();

        System.out.printf("%n规则:queryUser 的 QPS 阈值 %.0f,每格是连续请求 %d 次里 OK 的次数(10 = 没被限),"
                + "其余都是 BLOCKED;带 * 的格子跨过了整秒,不作数%n", QPS, BURST);
        System.out.printf("%-34s", "strategy / refResource");
        for (String p : PATHS) {
            System.out.printf("%11s", p);
        }
        System.out.println();

        row("DIRECT (control)", rule(RuleConstant.STRATEGY_DIRECT, null));
        for (String ref : REFS) {
            row("CHAIN " + ref, rule(RuleConstant.STRATEGY_CHAIN, ref));
        }

        // 单独看一件事:refResource 写成统一的 context 名时,/a 和 /b 是不是在抢同一个配额
        FlowRuleManager.loadRules(List.of(rule(RuleConstant.STRATEGY_CHAIN, unifiedName())));
        freshWindow();
        long start = System.currentTimeMillis();
        Cell a = burst("/a");
        Cell b = burst("/b");
        boolean crossed = start / 1000 != System.currentTimeMillis() / 1000;
        System.out.printf("%nCHAIN %s,同一秒内先 /a 后 /b:/a OK %d 次,/b OK %d 次%s%n",
                unifiedName(), a.ok(), b.ok(), crossed ? "(跨过了整秒,不作数)" : "");

        FlowRuleManager.loadRules(List.of());
        System.exit(SpringApplication.exit(ctx));
    }

    private String unifiedName() {
        return "sentinel_spring_web_context";
    }

    private void row(String label, FlowRule r) throws Exception {
        FlowRuleManager.loadRules(List.of(r));
        System.out.printf("%-34s", label);
        for (String p : PATHS) {
            freshWindow();
            System.out.printf("%11s", burst(p));
        }
        System.out.println();
    }

    private static FlowRule rule(int strategy, String ref) {
        FlowRule r = new FlowRule("queryUser");
        r.setGrade(RuleConstant.FLOW_GRADE_QPS);
        r.setCount(QPS);
        r.setStrategy(strategy);
        if (ref != null) {
            r.setRefResource(ref);
        }
        return r;
    }

    // 秒级统计是 1 秒的滑动窗口(两个 500ms 桶),等到下下个整秒再开始,前一格的请求就不会算进来
    private static void freshWindow() throws InterruptedException {
        long now = System.currentTimeMillis();
        long start = (now / 1000 + 2) * 1000 + 10;
        Thread.sleep(start - now);
    }

    // 一格的结果:OK 和 BLOCKED 各几次,这 10 个请求是否落在同一个整秒里
    record Cell(int ok, int blocked, boolean crossed) {
        @Override
        public String toString() {
            return ok + (crossed ? "*" : "");
        }
    }

    private Cell burst(String path) throws Exception {
        long start = System.currentTimeMillis();
        int ok = 0;
        int blocked = 0;
        for (int i = 0; i < BURST; i++) {
            if (get(path)) {
                ok++;
            } else {
                blocked++;
            }
        }
        if (ok + blocked != BURST) {
            throw new IllegalStateException(path + ": OK " + ok + " + BLOCKED " + blocked + " != " + BURST);
        }
        // 秒级窗口按整秒对齐,跨过整秒后前半段的请求会滑出统计,这一格就不可比了
        boolean crossed = start / 1000 != System.currentTimeMillis() / 1000;
        return new Cell(ok, blocked, crossed);
    }

    // 只认两种响应:200 + "OK"(放行)和 200 + "BLOCKED"(被 blockHandler 拦下)。
    // 404、500、429(Web 资源本身被限)或别的内容都说明实验没按预期走,直接报错退出,
    // 免得被当成"被限流"算进表里。
    private boolean get(String path) throws Exception {
        HttpRequest req = HttpRequest.newBuilder(URI.create(base + path))
                .timeout(Duration.ofSeconds(5))
                .GET()
                .build();
        HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString());
        String body = resp.body();
        if (resp.statusCode() == 200 && "OK".equals(body)) {
            return true;
        }
        if (resp.statusCode() == 200 && "BLOCKED".equals(body)) {
            return false;
        }
        throw new IllegalStateException("GET " + path + " -> HTTP " + resp.statusCode() + ": " + body);
    }

    private static void printTree() {
        System.out.println("\n调用树(Constants.ROOT 往下):");
        print(Constants.ROOT, 0);
    }

    private static void print(Node node, int depth) {
        DefaultNode n = (DefaultNode) node;
        System.out.println("  ".repeat(depth) + n.getId().getShowName());
        for (Node child : n.getChildList()) {
            print(child, depth + 1);
        }
    }
}

run.sh:

#!/bin/sh
# 用法:sh run.sh   (需要 JDK 17+ 和 Maven)
set -e
mvn -q -B package -DskipTests
for args in "--demo.unify=true" "--demo.unify=false" "--demo.unify=false --demo.method-prefix=true"; do
  echo "=================== $args"
  java -Dstdout.encoding=UTF-8 -jar target/chain-demo.jar \
    --server.port=0 --server.address=127.0.0.1 \
    --logging.level.root=warn --spring.main.banner-mode=off $args
done

运行 sh run.sh。每组实验 9 行 × 7 列,每格等一个新的整秒,一组要两分钟左右。三组的完整输出:

=================== --demo.unify=true
webContextUnify=true, httpMethodSpecify=false

调用树(Constants.ROOT 往下):
machine-root
  sentinel_spring_web_context
    /manual
    /b
    /async-fix
    /users/{id}
    /async
    /c
      viaWrapper
    /a
      queryUser
  sentinel_default_context
    queryUser

规则:queryUser 的 QPS 阈值 2,每格是连续请求 10 次里 OK 的次数(10 = 没被限),其余都是 BLOCKED;带 * 的格子跨过了整秒,不作数
strategy / refResource                     /a         /b         /c    /manual     /async /async-fix   /users/7
DIRECT (control)                            2          2          2          2          2          2          2
CHAIN /a                                   10         10         10         10         10         10         10
CHAIN GET:/a                               10         10         10         10         10         10         10
CHAIN /async-fix                           10         10         10         10         10         10         10
CHAIN /users/{id}                          10         10         10         10         10         10         10
CHAIN viaWrapper                           10         10         10         10         10         10         10
CHAIN manual_entry                         10         10         10         10         10         10         10
CHAIN sentinel_spring_web_context           2          2          2          2         10          2          2
CHAIN sentinel_default_context             10         10         10         10          2         10         10

CHAIN sentinel_spring_web_context,同一秒内先 /a 后 /b:/a OK 2 次,/b OK 0 次
=================== --demo.unify=false
webContextUnify=false, httpMethodSpecify=false

调用树(Constants.ROOT 往下):
machine-root
  /async
    /async
  /c
    /c
      viaWrapper
        queryUser
  /async-fix
    queryUser
    /async-fix
  /users/{id}
    /users/{id}
      queryUser
  /manual
    /manual
      queryUser
  /b
    /b
      queryUser
  /a
    /a
      queryUser
  sentinel_default_context
    queryUser

规则:queryUser 的 QPS 阈值 2,每格是连续请求 10 次里 OK 的次数(10 = 没被限),其余都是 BLOCKED;带 * 的格子跨过了整秒,不作数
strategy / refResource                     /a         /b         /c    /manual     /async /async-fix   /users/7
DIRECT (control)                            2          2          2          2          2          2          2
CHAIN /a                                    2         10         10         10         10         10         10
CHAIN GET:/a                               10         10         10         10         10         10         10
CHAIN /async-fix                           10         10         10         10         10          2         10
CHAIN /users/{id}                          10         10         10         10         10         10          2
CHAIN viaWrapper                           10         10         10         10         10         10         10
CHAIN manual_entry                         10         10         10         10         10         10         10
CHAIN sentinel_spring_web_context          10         10         10         10         10         10         10
CHAIN sentinel_default_context             10         10         10         10          2         10         10

CHAIN sentinel_spring_web_context,同一秒内先 /a 后 /b:/a OK 10 次,/b OK 10 次
=================== --demo.unify=false --demo.method-prefix=true
webContextUnify=false, httpMethodSpecify=true

调用树(Constants.ROOT 往下):
machine-root
  GET:/c
    GET:/c
      viaWrapper
        queryUser
  GET:/manual
    GET:/manual
      queryUser
  GET:/async-fix
    queryUser
    GET:/async-fix
  GET:/users/{id}
    GET:/users/{id}
      queryUser
  GET:/async
    GET:/async
  GET:/b
    GET:/b
      queryUser
  GET:/a
    GET:/a
      queryUser
  sentinel_default_context
    queryUser

规则:queryUser 的 QPS 阈值 2,每格是连续请求 10 次里 OK 的次数(10 = 没被限),其余都是 BLOCKED;带 * 的格子跨过了整秒,不作数
strategy / refResource                     /a         /b         /c    /manual     /async /async-fix   /users/7
DIRECT (control)                            2          2          2          2          2          2          2
CHAIN /a                                   10         10         10         10         10         10         10
CHAIN GET:/a                                2         10         10         10         10         10         10
CHAIN /async-fix                           10         10         10         10         10         10         10
CHAIN /users/{id}                          10         10         10         10         10         10         10
CHAIN viaWrapper                           10         10         10         10         10         10         10
CHAIN manual_entry                         10         10         10         10         10         10         10
CHAIN sentinel_spring_web_context          10         10         10         10         10         10         10
CHAIN sentinel_default_context             10         10         10         10          2         10         10

CHAIN sentinel_spring_web_context,同一秒内先 /a 后 /b:/a OK 10 次,/b OK 10 次

几点说明:

  • 端口随机,只监听 127.0.0.1。Sentinel 的日志写到当前目录的 target/sentinel-logs/。
  • 调用树的子节点存在 HashSet 里,打印顺序每次不同;默认配置下 queryUser 挂在哪个接口下面,取决于预热时谁先调到它。表格里的数字在本机多次运行都一样。
  • 每个响应都要校验:只接受 HTTP 200 加正文 OK(放行)或 BLOCKED(被 blockHandler 拦下)。其他状态码或内容,比如 404、500、Web 资源本身被限时的 429,都会直接抛异常,程序以非零状态退出,不会被当成“被限流”算进表里。每个请求有 5 秒超时,每格还会断言 OK 和 BLOCKED 加起来正好是 10。
  • 每格 10 个请求是顺序发的,本机都在几十毫秒内发完。秒级窗口按整秒对齐,如果 10 个请求跨过了整秒,前面的请求可能已经滑出统计,这一格会标上 *,表示不作数,重跑即可。本机多次运行没有出现过 *。
  • 输出里有中文,终端需要是 UTF-8。

内存粗测

NodeCost.java:

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.context.ContextUtil;
import java.lang.management.ManagementFactory;

/**
 * 粗测关掉统一 context 之后多出来的内存:
 * K 个接口(/api/0 ~ /api/K-1),每个接口都调同样 5 个下游资源。
 * 用法:java -XX:+UseSerialGC -cp sentinel-core.jar NodeCost.java <unify:true|false> <K> <秒数>
 */
public class NodeCost {

    public static void main(String[] args) throws Exception {
        System.setProperty("csp.sentinel.log.dir", "sentinel-logs");
        boolean unify = Boolean.parseBoolean(args[0]);
        int k = Integer.parseInt(args[1]);
        int seconds = Integer.parseInt(args[2]);

        // 持续打流量:分钟级统计有 60 个桶,跑满 60 秒以上桶才会全部建出来
        long end = System.currentTimeMillis() + seconds * 1000L;
        while (System.currentTimeMillis() < end) {
            long t0 = System.currentTimeMillis();
            for (int i = 0; i < k; i++) {
                request("/api/" + i, unify);
            }
            Thread.sleep(Math.max(0, 1000 - (System.currentTimeMillis() - t0)));
        }

        long used = usedAfterGc();
        System.out.printf("unify=%s K=%d contexts=%d heapUsed=%.1f MB%n",
                unify, k, ContextUtil.contextSize(), used / 1024.0 / 1024.0);
    }

    static void request(String api, boolean unify) throws Exception {
        ContextUtil.enter(unify ? "sentinel_spring_web_context" : api, "");
        Entry web = SphU.entry(api, EntryType.IN);
        for (int d = 1; d <= 5; d++) {
            SphU.entry("downstream-" + d).exit();
        }
        web.exit();
        ContextUtil.exit();
    }

    static long usedAfterGc() throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            System.gc();
            Thread.sleep(200);
        }
        return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
    }
}
mvn -q dependency:copy -Dartifact=com.alibaba.csp:sentinel-core:1.8.10 -DoutputDirectory=lib
java -XX:+UseSerialGC -Dstdout.encoding=UTF-8 -cp lib/sentinel-core-1.8.10.jar NodeCost.java true 1000 65
java -XX:+UseSerialGC -Dstdout.encoding=UTF-8 -cp lib/sentinel-core-1.8.10.jar NodeCost.java false 1000 65

我这边 65 秒的输出如下(跑了两次,另一次 unify=false 是 131.1 MB)。把最后一个参数换成 5 就是 5 秒那组,那组数字每次会差一两 MB:

unify=true K=1000 contexts=2 heapUsed=41.6 MB
unify=false K=1000 contexts=1001 heapUsed=132.3 MB

绝对值会随 JDK 版本、GC 和机器变化,用单文件方式启动时编译器本身也占一部分堆,所以只看两种配置之间的差值。

小结

  • 链路模式(STRATEGY_CHAIN)拿 refResource 和当前线程 context 的名字做 equals,对不上就放行,不报错。它比较的是入口,不是调用路径上的上一级资源。
  • context 名由线程里第一个 ContextUtil.enter 决定。Web 适配器默认把所有请求放进同一个 context(Spring MVC 是 sentinel_spring_web_context),所以写 URL 的链路规则全部不生效;控制台的调用树也会把共享资源只画在第一个调用者下面。
  • 默认值从 1.6.3 起是为了控制 context 和节点数量。关掉它(spring.cloud.sentinel.web-context-unify=false 或 setWebContextUnify(false)),每个入口一个 context,节点数变成“入口数 × 资源数”,实测稳态每个节点约 15 KB。
  • context 名必须有界。超过 2000 个之后,已有入口照常,新入口拿到 NullContext,这个请求经过的所有资源上的所有规则都不检查,只打一次 WARN。用路径模式或 UrlCleaner 收敛名字,对 WARN 和 ContextUtil.contextSize() 告警,入口限流不要只靠应用内这一层。
  • 关掉之后:refResource 要逐字等于入口名(路径模式、UrlCleaner、context path、方法前缀都会改变它);中间资源和请求里手动 enter 都不算入口;换线程会丢 context 掉进 sentinel_default_context,要在新线程里用同名重新 enter;每个入口一份配额,总量另配直接模式规则。
  • 只想按调用方区分,用来源和 limitApp;只有一两个入口要特殊对待,拆资源名比全局关 unify 更省。
— 文章结束 —返回文章归档 ↑

讨论

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