How Spring Cloud Sentinel Enforces Flow Control with @SentinelResource and Slot Chains
This article explains how Spring Cloud Sentinel initializes, uses @SentinelResource annotations, AOP interception, and a slot‑chain mechanism—including FlowSlot and DegradeSlot—to implement flow control, circuit breaking, and fallback handling in a Spring Boot microservice.
@SentinelResource Working Principle
After adding the spring-cloud-starter-alibaba-sentinel dependency, Spring Boot loads configuration from spring.factories, initializing classes such as SentinelWebAutoConfiguration and SentinelAutoConfiguration.
We use Sentinel version 1.8.0 for all examples.
The @SentinelResource annotation defines flow‑control and fallback rules directly on a method. Example:
@SentinelResource(value = "ResOrderGet",
fallback = "fallback",
fallbackClass = SentinelResourceExceptionHandler.class,
blockHandler = "blockHandler",
blockHandlerClass = SentinelResourceExceptionHandler.class)
@GetMapping("/order/get/{id}")
public CommonResult<StockModel> getStockDetails(@PathVariable Integer id) {
StockModel stockModel = new StockModel();
stockModel.setCode("STOCK=>1000");
stockModel.setId(id);
return CommonResult.success(stockModel);
}Spring AOP intercepts the getStockDetails method via the SentinelResourceAspect bean defined in SentinelAutoConfiguration:
@Bean
@ConditionalOnMissingBean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}The aspect defines a pointcut on methods annotated with @SentinelResource and an around advice that:
Retrieves annotation information.
Calls SphU.entry to apply flow‑control rules.
Executes the business method.
Handles BlockException via handleBlockException.
Handles other exceptions, optionally invoking a fallback method.
Thus the execution flow is: AOP interception → SphU.entry → business method → block/fallback handling.
Responsibility‑Chain Flow Control
The core of flow control is the SphU.entry method, which initializes a slot chain and processes the request.
Slot chain initialization occurs in lookProcessChain, which creates a DefaultSlotChainBuilder that loads all ProcessorSlot implementations via SPI, sorts them, and adds them to a ProcessorSlotChain:
public class DefaultSlotChainBuilder implements SlotChainBuilder {
@Override
public ProcessorSlotChain build() {
ProcessorSlotChain chain = new DefaultProcessorSlotChain();
List<ProcessorSlot> sortedSlotList = SpiLoader.loadPrototypeInstanceListSorted(ProcessorSlot.class);
for (ProcessorSlot slot : sortedSlotList) {
if (!(slot instanceof AbstractLinkedProcessorSlot)) {
continue;
}
chain.addLast((AbstractLinkedProcessorSlot<?>) slot);
}
return chain;
}
}The default slot order is:
NodeSelectorSlot
ClusterBuilderSlot
LogSlot
StatisticSlot
AuthoritySlot
SystemSlot
ParamFlowSlot
FlowSlot
DegradeSlot
Each slot implements an entry method. For example, FlowSlot checks flow rules and then fires the entry:
@Override
public void entry(Context context, ResourceWrapper resourceWrapper, DefaultNode node, int count,
boolean prioritized, Object... args) throws Throwable {
checkFlow(resourceWrapper, context, node, count, prioritized);
fireEntry(context, resourceWrapper, node, count, prioritized, args);
}The default controller decides whether a request can pass:
@Override
public boolean canPass(Node node, int acquireCount, boolean prioritized) {
int curCount = avgUsedTokens(node);
if (curCount + acquireCount > count) {
return false;
}
return true;
}
private int avgUsedTokens(Node node) {
if (node == null) {
return DEFAULT_AVG_USED_TOKENS;
}
return grade == RuleConstant.FLOW_GRADE_THREAD ? node.curThreadNum() : (int) (node.passQps());
}If the check fails, a FlowException (a subclass of BlockException) is thrown and later handled by SentinelResourceAspect. Statistics are recorded in StatisticSlot before the exception propagates.
DegradeSlot (Circuit Breaker)
The DegradeSlot implements circuit‑breaker logic with three states: OPEN, HALF_OPEN, and CLOSED, using ResponseTimeCircuitBreaker to evaluate response‑time thresholds.
Sentinel Web Interceptor
When @SentinelResource is not used, Sentinel applies flow control via a web interceptor defined in SentinelWebAutoConfiguration. The interceptor implements WebMvcConfigurer and registers a SentinelWebInterceptor bean:
@Bean
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true)
public SentinelWebInterceptor sentinelWebInterceptor(SentinelWebMvcConfig sentinelWebMvcConfig) {
return new SentinelWebInterceptor(sentinelWebMvcConfig);
}The interceptor’s preHandle method extracts the resource name, creates a context, and calls SphU.entry. If a BlockException occurs, it handles the block and aborts the request:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
try {
String resourceName = getResourceName(request);
if (StringUtil.isEmpty(resourceName)) {
return true;
}
if (increaseReferece(request, this.baseWebMvcConfig.getRequestRefName(), 1) != 1) {
return true;
}
String origin = parseOrigin(request);
String contextName = getContextName(request);
ContextUtil.enter(contextName, origin);
Entry entry = SphU.entry(resourceName, ResourceTypeConstants.COMMON_WEB, EntryType.IN);
request.setAttribute(baseWebMvcConfig.getRequestAttributeName(), entry);
return true;
} catch (BlockException e) {
try {
handleBlockException(request, response, e);
} finally {
ContextUtil.exit();
}
return false;
}
}References
Alibaba Sentinel Wiki
Martin Fowler – Circuit Breaker
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development Stories
Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
