Sentinel 源码导读(一):一行 SphU.entry 背后,初始化和 entryWithPriority 的每条分支
本文目录
这是 Sentinel 源码导读的第一篇。导读和前面的细节篇不一样:细节篇每篇盯一个功能点的坑,导读顺着一条调用链往下读,每一站讲清楚“这段代码在干什么、为什么这么写”,碰到值得单独展开的坑,就指到对应的细节篇。
整个系列从最常见的那一行开始:
try (Entry entry = SphU.entry("createOrder")) {
// 业务逻辑
} catch (BlockException e) {
// 被规则拦下
}
这一篇只走到 Slot 链的门口:SphU.entry 第一次被调用时 Sentinel 怎么初始化自己,以及 CtSph.entryWithPriority 怎么决定这次调用要不要交给 Slot 链、交出去以后出了状况怎么收场。Slot 链里面发生的事留给后面几篇。今天 Dubbo 那边的导读也是第一篇,从注解讲到启动;两边都从入口讲起,一边是框架怎么把服务跑起来,一边是一次调用怎么被保护起来。
先把这一篇的结论列出来:
- Sentinel 没有显式的启动方法。第一次读
Env.sph时触发Env的类初始化,静态块里调InitExecutor.doInit(),用SpiLoader加载并执行所有InitFunc。加载规则、ContextUtil.enter都不会触发它,SphU.entry会。doInit()还有别的调用方(集群流控的ClusterStateManager、Spring Cloud Alibaba 的 eager 配置、业务自己调),谁先抢到它里面的 CAS,初始化就在谁的线程里跑。 - 只有当
Env的类初始化线程抢到了 CAS,并发的首批SphU调用才会借 JVM 类初始化的锁一起等InitFunc跑完。如果别的调用方先抢到,Env静态块里的doInit()直接返回,这时的SphU.entry不保证InitFunc已经执行完。 Env的注释写着“初始化失败进程会退出”,1.8.10 的实际行为不是这样:某个InitFunc抛异常时,异常被吞掉、记一条 WARN,排在它后面的InitFunc全部跳过,以后也不会重试。META-INF/services里写了一个找不到的类,会让所有InitFunc都不执行。entryWithPriority的结果分三种状态,要分开看:- 前置短路,不进 Slot 链:
NullContext、全局开关关闭、Slot 链数量到了上限。只建一个 Entry 返回,不检查规则、不统计。 - 进了 Slot 链,中途抛了非
BlockException的异常:被 catch 住,记一条 INFO 日志,Entry 照样返回给调用方。这时排在前面的 Slot 可能已经执行过,状态取决于异常出在哪个 Slot。 - 还没进 try 就出错:拿 Context、找或建 Slot 链、构造 Entry 这几步在 try 外面,这里抛出的异常会直接抛给调用方,不会被放行。
- 前置短路,不进 Slot 链:
- 没有 Context 时用默认 Context,最外层 Entry 退出时自动清掉;显式
ContextUtil.enter的要自己exit。 - 被规则拦下时,
CtSph先把这个 Entry 退掉再抛BlockException。调用方的 catch 里不要再 exit 它,标准写法里那个 entry 变量本来也是null。
版本是 Sentinel 1.8.10,写这篇时 Maven Central 上最新的正式版(2026-12-04 核对,2.0.0-alpha 不算)。文中的源码片段都摘自这个 tag,有删节,Sentinel 以 Apache License 2.0 发布;流程图和伪代码是我按源码整理的,不是原文,每一节都给了对应源文件的链接。Slot 链和滑动窗口的全貌见总览那篇,本文只在路过时提一下。
这一篇走的路线
SphU.entry("createOrder")
└─ 读 Env.sph 第一次读:Env 类初始化
├─ sph = new CtSph()
└─ 静态块:InitExecutor.doInit() CAS 抢到才真正执行
├─ SpiLoader 加载 InitFunc,按 @Spi(order) 排序
└─ 按 @InitOrder 再排一次,逐个 init()
└─ CtSph:包成 StringResourceWrapper(name, OUT),count = 1,无参数
└─ entryWithPriority
├─ [try 外] 取当前线程的 Context
│ ├─ 是 NullContext → 前置短路
│ └─ 没有 → 进默认 Context
├─ [try 外] 全局开关关闭 → 前置短路
├─ [try 外] 找或建 Slot 链
│ └─ 到上限返回 null → 前置短路
├─ [try 外] 新建 Entry,挂到 Context 上
└─ [try 内] 进 Slot 链
├─ 通过 → 返回 Entry
├─ BlockException → 先 exit 这个 Entry,再抛出去
└─ 其它 Throwable → 记 INFO 日志,返回 Entry
图里标了 [try 外] 的步骤出了异常,会原样抛给调用方。
第一站:Env 的静态块
SphU 本身只是一组静态方法,每个重载都转给 Env.sph,例如 SphU.entry(name) 就是 Env.sph.entry(name, EntryType.OUT, 1, OBJECTS0)。
Env 是 SphU 这条路上的启动点,主体只有两句(摘录):
public static final Sph sph = new CtSph();
static {
// If init fails, the process will exit.
InitExecutor.doInit();
}
几件事值得看清楚。
触发时机是“第一次读 Env.sph”。 按 JLS 12.4.1,读一个类的非常量静态字段会触发这个类的初始化。SphU、SphO 的各个方法都读 Env.sph,所以第一次调用它们时 Env 才初始化。反过来,FlowRuleManager.loadRules 和 ContextUtil.enter 都不读 Env,单独调用它们不会触发;后面的实验里,规则加载了、Context 进出过一次,执行过的 InitFunc 还是空的。
字段先于静态块。 类初始化按源码顺序执行静态字段初始化和静态块,所以 sph 在 doInit() 之前就已经是一个 CtSph 了。某个 InitFunc 在同一个线程里调用 SphU.entry,不会读到 null:JVM 发现是当前线程自己在初始化这个类,直接放行(JLS 12.4.2 第 3 步),Env.sph 已经赋过值。
doInit() 不只 Env 一个调用方。 集群流控的 ClusterStateManager 静态块里调了一次;Spring Cloud Alibaba 配了 spring.cloud.sentinel.eager=true 时,SentinelApplicationContextInitializer 在应用上下文初始化阶段主动调它(2025.1.0.0 的源码,默认 false);业务代码也可以自己调。doInit() 开头用一个 AtomicBoolean 做 CAS,抢到的那一次真正执行,其余的调用立即返回,不会等抢到的那次跑完。
由此,“首批调用一起等”要分两种情况:
Env的类初始化线程抢到了 CAS(没有别的调用方先调过doInit(),这是只用SphU时的默认情况)。所有InitFunc在Env的类初始化里执行。按 JLS 12.4.2 第 2 步,别的线程发现类正在被另一个线程初始化,就阻塞到初始化结束。所以首调的耗时等于所有InitFunc的耗时之和,同时进来的那一批SphU调用都要等。实验 1 是这种情况:一个InitFunc睡了 300ms,两个同时发起的首调各花了 320ms 左右,初始化只在其中一个线程里跑。- 别的调用方先抢到了 CAS。比如另一个线程正在执行 eager 初始化,这时
Env的静态块里调doInit()直接返回,Env的类初始化很快结束,SphU.entry照常往下走。此刻InitFunc可能还没执行完,靠InitFunc注册的回调、数据源、命令中心都不保证已经就位。再调一次doInit()也不能当成“初始化已完成”的屏障:如果别的调用方已经抢到 CAS,这次调用同样立即返回。只有能保证启动流程里的这一次调用独占了首次执行(在它之前没有任何别的路径会触发doInit()),它返回才表示这次执行已经结束;而结束不等于成功,中途有InitFunc抛异常时,doInit()也是记一条日志就返回。所以要“依赖就绪以后才接流量”,应该等你实际依赖的东西各自就绪:自己的回调注册上了、数据源加载出了规则、需要的管理通道已经启动,各用各的检查,而不是靠再调一次doInit()。
第一种情况下有一个坑:InitFunc 里不要同步等待另一个会调用 SphU 的线程。 那个线程碰到 Env.sph 会等类初始化结束,而类初始化在等它。我写了一个 InitFunc,起一个线程去调 SphU.entry,然后 join(2000):2 秒到了那个线程还没进去,初始化结束后它才进去。不设超时的 join、Future.get()、CountDownLatch.await() 在这里就会一直卡住,而且发生在业务的第一次请求上。
接了控制台的应用,命令中心和心跳也是由 InitFunc 启动的。所以在初始化还没被触发、也没有 eager 之类的其它触发路径时,没有流量的应用在控制台上看不到;配了 eager 或者启动时已经有别的路径调过 doInit() 的,不在此列。这件事后续的细节篇会单独讲。
第二站:InitExecutor.doInit
InitExecutor 的 doInit() 按源码整理成伪代码是这样:
doInit():
if !initialized.compareAndSet(false, true): return # 只有第一次真正执行
try:
funcs = SpiLoader.of(InitFunc).loadInstanceListSorted() # 已按 @Spi(order) 排好
list = 按 @InitOrder 稳定插入排序(funcs) # 每个记一条 "Found init func"
for f in list:
f.init()
记一条 "Executing <类名> with order <n>" # init() 返回之后才记
catch Exception or Error:
记一条 WARN,printStackTrace,返回 # 不退出进程
两次排序
SpiLoader.loadInstanceListSorted() 先按 @Spi(order) 排一次(没有注解算 0),再按 @InitOrder 插入排序一次:值小的先执行,没有 @InitOrder 的算 Integer.MAX_VALUE,排最后。插入排序遇到相等的值会排在已有元素后面,所以 @InitOrder 相同时保持 SpiLoader 给出的顺序:先看 @Spi(order),再看 services 文件被读到的顺序。后者取决于类路径顺序,不要依赖它。
1.8.10 自带的几个 InitFunc:
| 模块 | InitFunc | @InitOrder | 做什么 |
|---|---|---|---|
| sentinel-transport-common | CommandCenterInitFunc |
-1 | 启动命令中心,控制台和应用之间的管理通道 |
| sentinel-transport-common | HeartbeatSenderInitFunc |
-1 | 定时给控制台发心跳 |
| sentinel-core | MetricCallbackInit |
无(最后) | 给 StatisticSlot 注册 MetricExtension 的回调 |
| sentinel-parameter-flow-control | ParamFlowStatisticSlotCallbackInit |
无(最后) | 给 StatisticSlot 注册热点参数线程数的计数回调 |
最后一行就是热点参数那篇提到的“线程数模式靠一个 InitFunc 注册回调”。
失败了会怎样
Env 静态块上那行注释说“If init fails, the process will exit”,doInit 的方法注释也说“the application will exit”。看代码,Exception 和 Error 都被 catch 住了,记一条 WARN、往标准错误打一段栈,然后正常返回。进程不会退出,SphU.entry 照常返回,Slot 链也照常工作。
真正的后果是另外三件事:
- 排在出错者后面的
InitFunc全部不执行。 循环被异常打断,后面的元素没有机会。自带的MetricCallbackInit和ParamFlowStatisticSlotCallbackInit都排在最后,你自己的InitFunc只要不是排在它们后面,抛一次异常就会把它们一起带走。按源码看,热点参数的线程数模式依赖的计数回调就注册不上了。 - 不会重试。 CAS 在 try 之前就把
initialized置成了true,再调多少次doInit()都直接返回。 - services 文件里有一个找不到的类,所有
InitFunc都不执行。SpiLoader在读 services 文件时遇到ClassNotFoundException、类型不匹配、别名重复,会抛SpiLoaderException。这发生在loadInstanceListSorted()里,一个InitFunc都还没跑。我在 services 文件里多写了一行不存在的类名试过,record 日志里只有一条 ERROR,原本应该执行的InitFunc都没有Executing记录。删类、改包名时忘了改 services 文件,就是这个效果。
所以写自己的 InitFunc 有几条底线:
init()里自己 catch 住能预料到的异常,记日志、降级,不要让它抛出去。拉远程配置失败、连不上数据源,都不应该连累别人的初始化。- 慢操作(网络、文件)放到后台线程,
init()里只启动它,不要等它。在第一种情况下,首调的耗时就是所有init()的总和。 - 需要顺序的,显式写
@InitOrder,不要靠类路径顺序。 - 上线后看一眼
sentinel-record.log里的[InitExecutor]:Found init func是找到了哪些,Executing ... with order是哪些真的执行完了。两组对不上,就是有人半路抛了异常。默认日志目录是${user.home}/logs/csp/。
SpiLoader 从哪里找
SpiLoader 读的是 META-INF/services/com.alibaba.csp.sentinel.init.InitFunc,和 JDK 的 ServiceLoader 用同一个文件格式(一行一个类名,# 开头是注释),但它是 Sentinel 自己实现的,多了 @Spi 上的排序、别名、单例/多例、默认实现这几样。几个和初始化有关的细节:
- 类加载器。 默认用加载
InitFunc接口的那个类加载器,也就是加载sentinel-core的那个;配了csp.sentinel.spi.classloader=context才改用线程上下文类加载器。在 Spring Boot 的 fat jar 里两者通常是同一个;如果sentinel-core放在容器的公共目录、InitFunc在应用自己的包里,默认配置下就找不到。 - 只加载一次。
SpiLoader也有自己的“已加载”标志,第一次加载之后不会再扫描。初始化之后才出现在类路径上的InitFunc,不会再被执行。 - 重复的类会跳过,不会报错。 同一个类在两个 jar 的 services 文件里都写了,第二次出现时记一条 WARN,跳过。
第三站:CtSph.entry 和 ResourceWrapper
到了 CtSph,entry(name, type, count, args) 只做一件事:把名字和入口类型包成 StringResourceWrapper,再转给 entryWithPriority,prioritized 填 false。
两个默认值要记住:SphU.entry(name) 是 EntryType.OUT、count 为 1、没有参数。OUT 的影响见系统保护那篇:系统规则只看 IN。没有参数,热点参数规则就没有值可查。
ResourceWrapper 的 equals 和 hashCode 只看名字(源码注释原话是“Only getName() is considered”)。所以同一个名字,不管是 IN 还是 OUT、是 StringResourceWrapper 还是 MethodResourceWrapper,都是同一个资源,共用一条 Slot 链、一份统计。每次调用各自的入口类型照样传给 Slot 链,按调用生效。
asyncEntry、entryWithPriority、entryWithType 这几个入口最后也都汇到 entryWithPriority 或者它的异步版本 asyncEntryWithPriorityInternal,分支结构一样,区别在异步版本通过以后会把 Entry 从当前线程的 Context 上摘下来。下面只看同步版本。
第四站:entryWithPriority 的三种状态
开头的路线图已经把 entryWithPriority 的步骤画全了。按“Slot 链执行到哪一步”,结果分成三种状态。
状态一:前置短路,Slot 链一个都没执行
三个条件,任何一个成立,都是新建一个 chain 为 null 的 CtEntry 直接返回:不检查规则、不统计,以后 exit 时也不走 Slot 链的 exit。调用方拿到的仍然是一个正常的 Entry,代码不需要区分。
NullContext。 ContextUtil 里 Context 的名字最多 2000 个(Constants.MAX_CONTEXT_NAME_SIZE,另有一个默认 Context)。超了以后,新名字的 enter 拿到的是一个 NullContext,放进当前线程,之后这个线程上的每一次 SphU.entry 都走这条短路,CtEntry 的构造函数里看到 NullContext 连调用树都不挂。上限怎么撞上、怎么防,见链路限流那篇。
全局开关关闭。 Constants.ON 是一个 volatile 的静态布尔字段,默认 true。关掉以后所有资源都走这条短路。它是给应急用的总闸:Sentinel 自己出了问题、或者规则配错导致大面积误拦时,一下子全部放开。core 里没有任何地方改它,生产环境里改它的是管理面,也就是命令中心那条通道。
一个能让全部规则失效的开关,要按管理权限对待:
- 授权控制:只有该有这个权限的人和系统能动它,操作要有记录。
- 隔离管理面:命令中心的端口只对控制台所在的可信网段开放,不和业务流量共用入口,不暴露到公网。
- 监控告警:把开关状态纳入监控,被关掉时及时告警;应急关闭以后,恢复也要有人负责确认。
开关切换不会把统计算乱,因为走不走 Slot 链在 Entry 创建时就定了(chain 有没有)。开着时进来的 Entry,关掉以后再 exit,照样走 Slot 链的 exit,并发线程数正常减回去;关着时进来的 Entry 不在 Slot 链里,exit 时什么都不做。实验 5 在一个独立的进程里直接改这个字段,验证了这一点。
Slot 链到了上限。 lookProcessChain 先无锁地查 chainMap,查不到才加锁;表里已经有 6000 个资源(Constants.MAX_SLOT_CHAIN_SIZE)就返回 null,否则建一条新链,复制整张表、放进去、替换引用。超过上限的新资源直接走短路、不报错,资源名里不要拼动态的 ID。这在总览里讲过,后续的细节篇会再展开链为 null 时到底跳过了什么。
新链怎么搭:SlotChainProvider 第一次用 SpiLoader 找 SlotChainBuilder,默认是 DefaultSlotChainBuilder,它再用 SpiLoader 加载 ProcessorSlot 的全部实现,按 @Spi(order) 排好串起来。NodeSelectorSlot、ClusterBuilderSlot 是 isSingleton = false,每条链各有一个实例,其它 Slot 全局共用一个。这是导读第三篇的内容。
没有 Context 不算短路。 大部分直接用 SphU.entry 的代码从不调 ContextUtil.enter,这时取到的 Context 是 null,CtSph 通过一个继承 ContextUtil 的内部类调 protected 的 trueEnter,进一个名叫 sentinel_default_context 的 Context。公开的 ContextUtil.enter 不允许用这个名字(会抛 ContextNameDefineException),所以要绕这一下。默认 Context 的入口节点在 ContextUtil 的静态块里就建好了,永远在那 2000 个名字的表里,不会拿到 NullContext,后面照常进 Slot 链。
自动进的就自动出:CtEntry 退出时,如果它是最外层(没有父 Entry)、而且当前是默认 Context,就顺手 ContextUtil.exit()。显式 enter 的 Context 没有这个待遇,最外层 Entry 退出后它还留在线程里,要自己 ContextUtil.exit()。实验 3 两种都走了一遍。Context 和调用树是下一篇导读的主题。
状态二:进了 Slot 链
先建 Entry,再进链,这一段摘录如下:
Entry e = new CtEntry(resourceWrapper, chain, context, count, args);
try {
chain.entry(context, resourceWrapper, null, count, prioritized, args);
} catch (BlockException e1) {
e.exit(count, args);
throw e1;
} catch (Throwable e1) {
// This should not happen, unless there are errors existing in Sentinel internal.
RecordLog.info("Sentinel unexpected exception", e1);
}
return e;
顺序很重要:CtEntry 的构造函数里,新 Entry 已经挂到 Context 上成了 curEntry,父 Entry 是原来的 curEntry。然后 Slot 链才开始跑,Slot 里取 context.getCurEntry() 拿到的就是这次调用。
通过:返回 Entry,业务代码执行完再 exit。
被规则拦下(BlockException):CtSph 在把异常抛给你之前先调了 e.exit(count, args)。这一步做了三件事:
- 走一遍 Slot 链的
exit。StatisticSlot在 entry 阶段已经把BlockException记到了curEntry上,exit 时看到有 block 错误,就不记成功数和 RT、不减线程数(拦下的请求本来也没加过)。 - 把
curEntry恢复成父 Entry。被拒的这个 Entry 从调用树上摘掉,后面的调用不会挂到它下面。 - 如果它是默认 Context 里的最外层 Entry,顺手把默认 Context 也退掉。
所以调用方的 catch 里不需要、也不应该再 exit 这个 Entry。标准写法里本来就碰不到它:
Entry entry = null;
try {
entry = SphU.entry("createOrder"); // 抛异常时赋值没有发生,entry 还是 null
// 业务逻辑
} catch (BlockException e) {
// 处理被拒
} finally {
if (entry != null) {
entry.exit();
}
}
try-with-resources 也一样:资源初始化表达式抛了异常,close() 不会被调用。实验 4 在 catch 里看了一眼:显式 Context 里,curEntry 已经回到了外层的 demo-outer;默认 Context 里,Context 已经没了。
其它异常(非 BlockException 的 Throwable):某个 Slot 有 bug、某个扩展的回调抛了运行时异常,都会落到最后一个 catch。CtSph 记一条 INFO 日志,然后把 Entry 当成通过返回。和状态一不同,这时 Slot 链已经开始执行,排在出错位置之前的 Slot 可能已经做完了自己的那一份 entry 逻辑,统计和调用树处于什么状态,取决于异常出在哪个 Slot;这个 Entry 以后 exit 时也会走 Slot 链的 exit。这是 Sentinel“保护组件不能成为故障点”的取舍,代价是日志只有 INFO 级别,混在 record 日志里不容易发现。自己写 Slot 或者 StatisticSlot 回调这类扩展时,留意 record 日志里有没有 Sentinel unexpected exception。
状态三:还没进 try 就出错
路线图里 [try 外] 的几步,取 Context、进默认 Context、lookProcessChain(包括第一次建链时加载 SlotChainBuilder、ProcessorSlot)、构造 CtEntry,都不在上面那个 try 里。这里抛出的异常不会被吞掉,会原样抛给调用 SphU.entry 的代码。比如 ProcessorSlot 的 services 文件里写了一个找不到的类,建链时 SpiLoader 抛出的异常就会直接到业务代码手里。所以“Sentinel 自己出错一律放行”这句话只对状态二成立,不能概括成任意内部异常。
实验
下面是一个只依赖 Maven Central 上的 sentinel-core 和 sentinel-parameter-flow-control 1.8.10 的独立示例,JDK 8 及以上、Maven 3 能跑。第二个依赖只是为了让它自带的 InitFunc 出现在列表里。
mvn -q compile exec:java
mvn -q exec:java -Ddemo.brokenInit=true
输出里有中文,终端用 UTF-8。示例把 Sentinel 的日志写到 target/sentinel-logs/ 下每次运行自己的目录里,不碰 ~/logs/csp。
- 实验 1(
Env的类初始化线程抢到 CAS 的情况,示例里没有别的doInit()调用方):规则加载、Context 进出各一次,看InitFunc有没有执行;两个线程同时发起第一次SphU.entry;之后从 record 日志里挑出[InitExecutor]的记录。三个自定义的InitFunc:EarlyInit(@InitOrder(-10),睡 300ms)、BrokenInit(@InitOrder(0),带-Ddemo.brokenInit=true时抛异常)、LateInit(没有@InitOrder)。 - 实验 2(只在
-Ddemo.brokenInit=true时跑):初始化失败以后,进程、重试和规则的状态。 - 实验 3:默认 Context 和显式 Context 的退出。
- 实验 4:被拒以后 Context 上的
curEntry。 - 实验 5:全局开关关掉、打开,以及跨越开关切换的 Entry 对并发线程数的影响。实验在这个独立的教学进程里直接写
Constants.ON字段,不涉及任何管理通道。
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>
<groupId>demo</groupId>
<artifactId>sentinel-entry-walk</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.release>8</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-parameter-flow-control</artifactId>
<version>1.8.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<mainClass>demo.EntryWalkDemo</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
src/main/resources/META-INF/services/com.alibaba.csp.sentinel.init.InitFunc:
demo.EarlyInit
demo.BrokenInit
demo.LateInit
src/main/java/demo/Clock.java:
package demo;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/** 打印用的小工具:时间从 main 开始算,顺便记下哪些 InitFunc 跑过。 */
final class Clock {
static final long START = System.nanoTime();
static final List<String> EXECUTED = new CopyOnWriteArrayList<>();
static long ms() {
return (System.nanoTime() - START) / 1_000_000;
}
static void log(String msg) {
System.out.printf("[%5d ms][%s] %s%n", ms(), Thread.currentThread().getName(), msg);
}
private Clock() {}
}
src/main/java/demo/EarlyInit.java:
package demo;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.init.InitOrder;
/** 排在最前面,故意睡 300ms,模拟启动命令中心、拉远程规则这类慢初始化。 */
@InitOrder(-10)
public class EarlyInit implements InitFunc {
@Override
public void init() throws Exception {
Clock.log("EarlyInit 开始(@InitOrder(-10))");
Thread.sleep(300);
Clock.EXECUTED.add("EarlyInit");
Clock.log("EarlyInit 结束");
}
}
src/main/java/demo/BrokenInit.java:
package demo;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.init.InitOrder;
/** 加 -Ddemo.brokenInit=true 时抛异常,模拟一个初始化失败的 InitFunc。 */
@InitOrder(0)
public class BrokenInit implements InitFunc {
@Override
public void init() throws Exception {
if (Boolean.getBoolean("demo.brokenInit")) {
Clock.log("BrokenInit 抛出异常(@InitOrder(0))");
throw new IllegalStateException("模拟:初始化失败");
}
Clock.EXECUTED.add("BrokenInit");
Clock.log("BrokenInit 正常结束(@InitOrder(0))");
}
}
src/main/java/demo/LateInit.java:
package demo;
import com.alibaba.csp.sentinel.init.InitFunc;
/** 没有 @InitOrder,按 Integer.MAX_VALUE 排,和 Sentinel 自带的两个 InitFunc 同一档。 */
public class LateInit implements InitFunc {
@Override
public void init() {
Clock.EXECUTED.add("LateInit");
Clock.log("LateInit 执行(没有 @InitOrder)");
}
}
src/main/java/demo/EntryWalkDemo.java:
package demo;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import com.alibaba.csp.sentinel.Constants;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.context.Context;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.init.InitExecutor;
import com.alibaba.csp.sentinel.node.ClusterNode;
import com.alibaba.csp.sentinel.slotchain.ResourceWrapper;
import com.alibaba.csp.sentinel.slots.block.BlockException;
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 com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot;
public class EntryWalkDemo {
private static final String LIMITED = "demo-limited";
public static void main(String[] args) throws Exception {
// 日志写到 target 下本次运行自己的目录,不碰 ~/logs/csp。必须在任何 Sentinel 类加载之前设置。
Path logDir = Paths.get("target", "sentinel-logs", "run-" + System.currentTimeMillis());
System.setProperty("csp.sentinel.log.dir", logDir.toAbsolutePath().toString());
Clock.log("main 开始,brokenInit=" + Boolean.getBoolean("demo.brokenInit"));
initTiming();
printInitLog(logDir);
if (Boolean.getBoolean("demo.brokenInit")) {
brokenInit();
return;
}
defaultContext();
blockedEntryIsExited();
globalSwitch();
}
/** 1. 加载规则、进 Context 都不会触发初始化,第一次 SphU.entry 才会;并发的首调一起等。 */
static void initTiming() throws Exception {
System.out.println("\n== 1. 初始化时机 ==");
FlowRule rule = new FlowRule(LIMITED);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(1);
FlowRuleManager.loadRules(Collections.singletonList(rule));
Clock.log("规则已加载,执行过的 InitFunc:" + Clock.EXECUTED);
ContextUtil.enter("demo-entrance");
ContextUtil.exit();
Clock.log("进出过一次 Context,执行过的 InitFunc:" + Clock.EXECUTED);
CountDownLatch go = new CountDownLatch(1);
Thread[] threads = new Thread[2];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
try {
go.await();
long t0 = System.nanoTime();
try (Entry ignored = SphU.entry("demo-first")) {
Clock.log("首次 SphU.entry 返回,耗时 " + (System.nanoTime() - t0) / 1_000_000 + " ms");
}
} catch (Exception e) {
Clock.log("意外:" + e);
}
}, "caller-" + (i + 1));
threads[i].start();
}
go.countDown();
for (Thread t : threads) {
t.join();
}
long t0 = System.nanoTime();
try (Entry ignored = SphU.entry("demo-first")) {
Clock.log("再调一次,耗时 " + (System.nanoTime() - t0) / 1_000_000 + " ms,执行过的 InitFunc:" + Clock.EXECUTED);
}
}
/** 2. 某个 InitFunc 抛异常:进程不退出,排在它后面的全部跳过,也不会再重试。 */
static void brokenInit() throws Exception {
System.out.println("\n== 2. InitFunc 抛异常之后 ==");
Clock.log("进程还在,执行过的 InitFunc:" + Clock.EXECUTED);
InitExecutor.doInit();
Clock.log("手动再调 InitExecutor.doInit(),执行过的 InitFunc:" + Clock.EXECUTED);
int passed = 0;
int blocked = 0;
for (int i = 0; i < 3; i++) {
try (Entry ignored = SphU.entry(LIMITED)) {
passed++;
} catch (BlockException e) {
blocked++;
}
}
Clock.log("规则照常生效:通过 " + passed + ",被拒 " + blocked);
}
/** 把 Sentinel 自己的 record 日志里和 InitExecutor 有关的行挑出来。 */
static void printInitLog(Path logDir) throws Exception {
System.out.println("\nsentinel-record.log 里 InitExecutor 的记录:");
// 文件名带日期后缀,例如 sentinel-record.log.2026-12-04.0
try (DirectoryStream<Path> files = Files.newDirectoryStream(logDir, "sentinel-record.log*")) {
for (Path record : files) {
for (String line : Files.readAllLines(record, StandardCharsets.UTF_8)) {
int idx = line.indexOf("[InitExecutor]");
if (idx >= 0) {
System.out.println(" " + line.substring(idx));
}
}
}
}
}
/** 3. 没有 ContextUtil.enter 时用默认 Context,最外层 entry 退出时自动清掉。 */
static void defaultContext() throws Exception {
System.out.println("\n== 3. 默认 Context ==");
try (Entry ignored = SphU.entry("demo-a")) {
Context ctx = ContextUtil.getContext();
Clock.log("entry 里:context=" + ctx.getName() + ",curEntry=" + name(ctx.getCurEntry()));
}
Clock.log("exit 之后:ContextUtil.getContext()=" + ContextUtil.getContext());
ContextUtil.enter("demo-entrance");
try (Entry ignored = SphU.entry("demo-a")) {
Clock.log("显式 enter 后:context=" + ContextUtil.getContext().getName());
}
Clock.log("entry exit 之后:context=" + ContextUtil.getContext().getName() + "(还在,要自己 exit)");
ContextUtil.exit();
Clock.log("ContextUtil.exit() 之后:" + ContextUtil.getContext());
}
/** 4. 被拒的 entry 在抛 BlockException 之前已经被 CtSph 退掉了。 */
static void blockedEntryIsExited() throws Exception {
System.out.println("\n== 4. 被拒时先 exit 再抛 ==");
Thread.sleep(1100); // 等上一秒的统计滑出窗口
ContextUtil.enter("demo-entrance");
Entry outer = SphU.entry("demo-outer");
for (int i = 1; i <= 2; i++) {
try (Entry ignored = SphU.entry(LIMITED)) {
Clock.log("第 " + i + " 次通过,curEntry=" + name(ContextUtil.getContext().getCurEntry()));
} catch (BlockException e) {
Clock.log("第 " + i + " 次被拒(" + e.getClass().getSimpleName() + "),catch 里 curEntry="
+ name(ContextUtil.getContext().getCurEntry()));
}
}
outer.exit();
ContextUtil.exit();
try (Entry ignored = SphU.entry(LIMITED)) {
Clock.log("意外通过");
} catch (BlockException e) {
Clock.log("默认 Context 下被拒,catch 里 ContextUtil.getContext()=" + ContextUtil.getContext());
}
}
/** 5. 全局开关 Constants.ON:关掉时不建 Slot 链、不检查、不统计。 */
static void globalSwitch() throws Exception {
System.out.println("\n== 5. 全局开关 ==");
Thread.sleep(1100);
ClusterNode node = ClusterBuilderSlot.getClusterNode(LIMITED);
long before = node.totalPass();
Constants.ON = false;
int passed = 0;
for (int i = 0; i < 5; i++) {
try (Entry ignored = SphU.entry(LIMITED)) {
passed++;
} catch (BlockException e) {
// 开关关闭时走不到这里
}
}
Clock.log("开关关闭:5 次调用通过 " + passed + " 次,统计里的 pass 增加了 " + (node.totalPass() - before));
Constants.ON = true;
passed = 0;
int blocked = 0;
for (int i = 0; i < 3; i++) {
try (Entry ignored = SphU.entry(LIMITED)) {
passed++;
} catch (BlockException e) {
blocked++;
}
}
Clock.log("开关打开:3 次调用通过 " + passed + ",被拒 " + blocked);
Entry held = SphU.entry("demo-held");
ClusterNode heldNode = ClusterBuilderSlot.getClusterNode("demo-held");
Clock.log("开着时进入 demo-held,并发线程数=" + heldNode.curThreadNum());
Constants.ON = false;
held.exit();
Constants.ON = true;
Clock.log("关掉开关后再 exit,并发线程数=" + heldNode.curThreadNum());
}
private static String name(Entry e) {
if (e == null) {
return "null";
}
ResourceWrapper r = e.getResourceWrapper();
return r.getName();
}
}
结果
在一台 4 核的云上 Linux 虚拟机、OpenJDK 21 上各跑了两次,结论每次都一样;毫秒数和执行初始化的是哪个线程每次略有不同。下面是其中一次的输出,Sentinel 启动时自己打的几行 INFO: Sentinel log ... 省略了。
不带参数:
[ 0 ms][demo.EntryWalkDemo.main()] main 开始,brokenInit=false
== 1. 初始化时机 ==
[ 28 ms][demo.EntryWalkDemo.main()] 规则已加载,执行过的 InitFunc:[]
[ 32 ms][demo.EntryWalkDemo.main()] 进出过一次 Context,执行过的 InitFunc:[]
[ 43 ms][caller-2] EarlyInit 开始(@InitOrder(-10))
[ 343 ms][caller-2] EarlyInit 结束
[ 344 ms][caller-2] BrokenInit 正常结束(@InitOrder(0))
[ 344 ms][caller-2] LateInit 执行(没有 @InitOrder)
[ 358 ms][caller-2] 首次 SphU.entry 返回,耗时 320 ms
[ 358 ms][caller-1] 首次 SphU.entry 返回,耗时 320 ms
[ 359 ms][demo.EntryWalkDemo.main()] 再调一次,耗时 0 ms,执行过的 InitFunc:[EarlyInit, BrokenInit, LateInit]
sentinel-record.log 里 InitExecutor 的记录:
[InitExecutor] Found init func: demo.EarlyInit
[InitExecutor] Found init func: demo.BrokenInit
[InitExecutor] Found init func: demo.LateInit
[InitExecutor] Found init func: com.alibaba.csp.sentinel.metric.extension.MetricCallbackInit
[InitExecutor] Found init func: com.alibaba.csp.sentinel.init.ParamFlowStatisticSlotCallbackInit
[InitExecutor] Executing demo.EarlyInit with order -10
[InitExecutor] Executing demo.BrokenInit with order 0
[InitExecutor] Executing demo.LateInit with order 2147483647
[InitExecutor] Executing com.alibaba.csp.sentinel.metric.extension.MetricCallbackInit with order 2147483647
[InitExecutor] Executing com.alibaba.csp.sentinel.init.ParamFlowStatisticSlotCallbackInit with order 2147483647
== 3. 默认 Context ==
[ 360 ms][demo.EntryWalkDemo.main()] entry 里:context=sentinel_default_context,curEntry=demo-a
[ 361 ms][demo.EntryWalkDemo.main()] exit 之后:ContextUtil.getContext()=null
[ 361 ms][demo.EntryWalkDemo.main()] 显式 enter 后:context=demo-entrance
[ 361 ms][demo.EntryWalkDemo.main()] entry exit 之后:context=demo-entrance(还在,要自己 exit)
[ 361 ms][demo.EntryWalkDemo.main()] ContextUtil.exit() 之后:null
== 4. 被拒时先 exit 再抛 ==
[ 1462 ms][demo.EntryWalkDemo.main()] 第 1 次通过,curEntry=demo-limited
[ 1470 ms][demo.EntryWalkDemo.main()] 第 2 次被拒(FlowException),catch 里 curEntry=demo-outer
[ 1470 ms][demo.EntryWalkDemo.main()] 默认 Context 下被拒,catch 里 ContextUtil.getContext()=null
== 5. 全局开关 ==
[ 2571 ms][demo.EntryWalkDemo.main()] 开关关闭:5 次调用通过 5 次,统计里的 pass 增加了 0
[ 2572 ms][demo.EntryWalkDemo.main()] 开关打开:3 次调用通过 1,被拒 2
[ 2573 ms][demo.EntryWalkDemo.main()] 开着时进入 demo-held,并发线程数=1
[ 2573 ms][demo.EntryWalkDemo.main()] 关掉开关后再 exit,并发线程数=0
带 -Ddemo.brokenInit=true:
[ 0 ms][demo.EntryWalkDemo.main()] main 开始,brokenInit=true
== 1. 初始化时机 ==
[ 37 ms][demo.EntryWalkDemo.main()] 规则已加载,执行过的 InitFunc:[]
[ 40 ms][demo.EntryWalkDemo.main()] 进出过一次 Context,执行过的 InitFunc:[]
[ 49 ms][caller-1] EarlyInit 开始(@InitOrder(-10))
[ 349 ms][caller-1] EarlyInit 结束
[ 350 ms][caller-1] BrokenInit 抛出异常(@InitOrder(0))
java.lang.IllegalStateException: 模拟:初始化失败
at demo.BrokenInit.init(BrokenInit.java:13)
at com.alibaba.csp.sentinel.init.InitExecutor.doInit(InitExecutor.java:53)
at com.alibaba.csp.sentinel.Env.<clinit>(Env.java:36)
at com.alibaba.csp.sentinel.SphU.entry(SphU.java:85)
at demo.EntryWalkDemo.lambda$initTiming$0(EntryWalkDemo.java:67)
at java.base/java.lang.Thread.run(Thread.java:1583)
[ 362 ms][caller-1] 首次 SphU.entry 返回,耗时 319 ms
[ 362 ms][caller-2] 首次 SphU.entry 返回,耗时 319 ms
[ 363 ms][demo.EntryWalkDemo.main()] 再调一次,耗时 0 ms,执行过的 InitFunc:[EarlyInit]
sentinel-record.log 里 InitExecutor 的记录:
[InitExecutor] Found init func: demo.EarlyInit
[InitExecutor] Found init func: demo.BrokenInit
[InitExecutor] Found init func: demo.LateInit
[InitExecutor] Found init func: com.alibaba.csp.sentinel.metric.extension.MetricCallbackInit
[InitExecutor] Found init func: com.alibaba.csp.sentinel.init.ParamFlowStatisticSlotCallbackInit
[InitExecutor] Executing demo.EarlyInit with order -10
[InitExecutor] WARN: Initialization failed
== 2. InitFunc 抛异常之后 ==
[ 364 ms][demo.EntryWalkDemo.main()] 进程还在,执行过的 InitFunc:[EarlyInit]
[ 365 ms][demo.EntryWalkDemo.main()] 手动再调 InitExecutor.doInit(),执行过的 InitFunc:[EarlyInit]
[ 372 ms][demo.EntryWalkDemo.main()] 规则照常生效:通过 1,被拒 2
逐条对一下:
- 规则加载了、Context 进出过一次,
InitFunc一个都没执行;第一次SphU.entry才触发。三个InitFunc都在同一个调用者线程里按@InitOrder执行,另一个线程什么都没执行,但两个线程的首调都花了 320ms 左右,就是EarlyInit的 300ms 加上加载类的时间。这是因为初始化由Env的类初始化触发;如果有别的调用方先调过doInit(),就不是这个结果。第二次调用不到 1ms。这里的毫秒数只是这一次运行的观察,取决于机器和你的InitFunc做了什么。 - record 日志里先是
Found init func,再是Executing。没有@InitOrder的三个(LateInit和两个自带的)都是2147483647,排在最后。 - 初始化失败的那次:
EarlyInit执行了,BrokenInit抛了异常,栈打在标准错误上;LateInit、MetricCallbackInit、ParamFlowStatisticSlotCallbackInit在日志里只有Found,没有Executing。进程没退出,SphU.entry照常返回,再手动调InitExecutor.doInit()什么都不发生,限流规则照常生效(QPS 1,三次里过 1 拒 2)。 - 默认 Context 在 exit 后自动没了;显式
enter的demo-entrance在 Entry 退出后还在,ContextUtil.exit()之后才清掉。 - 第 2 次调用
demo-limited被拒,catch 里curEntry已经是外层的demo-outer,被拒的那个 Entry 已经退掉了;默认 Context 下被拒,catch 里 Context 已经是null。 - 开关关闭时 5 次调用都返回了 Entry,
ClusterNode的通过数一次都没加,说明没走 Slot 链;打开后规则立刻恢复生效,3 次过 1 拒 2。开着时进入、关掉后 exit 的那个 Entry,并发线程数正常从 1 回到 0。
小结
- 第一次读
Env.sph(也就是第一次调用SphU/SphO)触发类初始化,静态块里调InitExecutor.doInit()。规则加载、ContextUtil.enter不会触发。doInit()也可能被ClusterStateManager、Spring Cloud Alibaba 的spring.cloud.sentinel.eager=true或业务代码先调,谁先抢到 CAS,初始化就在谁的线程里跑。 - 只有
Env的类初始化线程抢到 CAS 时,并发的首批SphU调用才会一起等InitFunc跑完;别的调用方先抢到时,SphU.entry不保证InitFunc已经执行完。再调一次doInit()不是屏障:只有启动流程能保证独占首次调用时,它返回才表示这次执行已结束,而且结束不等于成功;要“依赖就绪才接流量”,就分别检查实际依赖的回调、数据源等是否就绪。InitFunc要快,慢操作放后台,不要在里面同步等待会调用SphU的其它线程。 - 没有流量就在控制台上看不到,只适用于初始化还没被触发、也没有 eager 之类其它触发路径的情况。
InitFunc抛异常不会让进程退出(和注释说的不一样),但排在它后面的全部跳过、不重试,包括排在最后的两个自带回调;services 文件里一个找不到的类会让所有InitFunc都不执行。上线后对一下 record 日志里Found和Executing的数量。SphU.entry(name)默认EntryType.OUT、count 1、没有参数;资源只按名字区分。entryWithPriority的结果分三种:NullContext、全局开关关闭、Slot 链到上限这三种是前置短路,一个 Slot 都不执行;进了 Slot 链以后抛出非BlockException的异常会被 catch 住放行,但前面的 Slot 可能已经执行过,日志只有 INFO 级别;try 外面的步骤(取 Context、找或建 Slot 链、构造 Entry)出错会直接抛给调用方,不放行。- 被拒时
CtSph先 exit 再抛BlockException,catch 里不要再 exit;默认 Context 跟着最外层 Entry 自动退出,显式 Context 要自己退。 - 全局开关能让全部规则失效,按管理权限对待:授权控制、隔离管理面、开关状态纳入监控告警。
下一篇导读进 Context:ContextUtil.enter 建了什么、EntranceNode 和 DefaultNode 怎么组成调用树、同一个资源在不同入口下为什么有不同的统计节点。再往后是 Slot 链怎么搭,以及前三个 Slot 各自做了什么。
讨论
点击后加载 giscus 讨论。登录与发表由你自行操作。