Simple Sentinel Examples
As microservices architectures become ubiquitous, stability challenges such as cascading service failures and system overloads are increasingly prominent. Developed by Alibaba, Sentinel is a lightweight, powerful flow-control component designed specifically to tackle these pain points. By taking "traffic" as its primary entry point, Sentinel safeguards the resilience of distributed systems across multiple dimensions, including traffic shaping, circuit breaking, system adaptive protection, and more.
This article guides you through a straightforward Java example to help you quickly grasp Sentinel's core capability: Flow Control.
Before jumping into the code, let's look at two foundational concepts in Sentinel:
- Resource: A standard and flexible concept in Sentinel. It can represent virtually anything within a Java application—such as a piece of code defined by the Sentinel API, a specific service method, or even an inbound HTTP request.
- Rule: A policy tailored to the real-time runtime state of a resource. Common types include flow control rules, circuit breaking rules, and system protection rules.
To begin, create a standard Maven project and include the Sentinel core dependency in yourpom.xmlconfiguration file:
<dependencies>
<!-- Sentinel Core Dependency -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.6</version>
</dependency>
</dependencies>
Make sure your project is running on JDK 1.8 or higher.
Writing Your First Sentinel Example
In this demonstration, we will simulate a business operation and configure a flow rule that permits a maximum of 2 requests per second. Any incoming traffic exceeding this threshold will trigger an exception, allowing us to handle it gracefully through fallback logic.
Create a file named SentinelDemo.java with the following implementation:
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
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 java.util.ArrayList;
import java.util.List;
public class SentinelDemo {
public static void main(String[] args) {
// 1. Initialize flow control rules
initFlowRules();
// 2. Simulate a loop of incoming requests
for (int i = 1; i <= 5; i++) {
// Protect the block using try-with-resources
try (Entry entry = SphU.entry("doSomething")) {
// ---- Protected business logic ----
System.out.println(System.currentTimeMillis() + " [SUCCESS] Executed business logic successfully. Request ID: " + i);
} catch (BlockException e) {
// ---- Fallback logic when flow is blocked ----
System.out.println(System.currentTimeMillis() + " [BLOCKED] System is busy, please try again later! Request ID: " + i);
}
// Short sleep interval to simulate request pacing
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Set up basic flow control rules
*/
private static void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
// Define the target resource name
rule.setResource("doSomething");
// Set the threshold type (QPS mode)
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
// Set the QPS limit threshold to 2
rule.setCount(2);
rules.add(rule);
// Load the configured rules into Sentinel
FlowRuleManager.loadRules(rules);
}
}
Code Walkthrough
From the example above, we can break down standard Sentinel integration into three simple steps:
- Define a Resource: Wrap the code snippet requiring protection using
SphU.entry("resourceName"). Utilizing Java'stry-with-resourcessyntax is strongly recommended to ensure that entries are cleanly and correctly exited. - Define Rules: Instantiate a
FlowRuleobject to configure runtime constraints. In our code, we targeted the resource nameddoSomething, set the threshold type to QPS, and specified a limit of2. This ensures the resource can be invoked at most twice per second. - Handle Block Exceptions: Whenever traffic surpasses the predefined threshold, Sentinel throws a
BlockException. We catch this exception inside thecatchblock to execute graceful degradation or rejection logic.
Execution and Test Results
Run the SentinelDemo main application, and you will see console output similar to the following:
1680000000001 [SUCCESS] Executed business logic successfully. Request ID: 1
1680000000305 [SUCCESS] Executed business logic successfully. Request ID: 2
1680000000610 [BLOCKED] System is busy, please try again later! Request ID: 3
1680000000915 [SUCCESS] Executed business logic successfully. Request ID: 4
1680000001220 [SUCCESS] Executed business logic successfully. Request ID: 5
As illustrated by the logs, because the QPS threshold was capped at 2 and requests were fired consecutively within a short span, the third request triggered the flow control mechanism and was routed into the catch block. This successfully shielded the downstream logic from being overwhelmed by sudden traffic spikes.
Conclusion
This article walked through a minimal Java example to demonstrate how to integrate Sentinel and configure hardcoded QPS flow control rules. In real-world enterprise environments, Sentinel is typically integrated with microservices frameworks like Spring Cloud or Apache Dubbo, leveraging the Sentinel Dashboard for dynamic, visual rule management. Mastering this fundamental sample marks a vital step toward building highly available microservice architectures.