1. Overview
1.概述
As the name suggests, Sentinel is a powerful guard for microservices. It offers features like flow control, concurrency limiting, circuit breaking, and adaptive system protection to guarantee their reliability. It’s an open-source component actively maintained by Alibaba Group. In addition, it’s officially a part of the Spring Cloud Circuit Breaker.
顾名思义,Sentinel是一个强大的微服务防护系统。它提供了流量控制、并发限制、断路和自适应系统保护等功能,以保证其可靠性。它是一个由阿里巴巴集团积极维护的开源组件。此外,它正式成为Spring Cloud Circuit Breaker的一部分。
In this tutorial, we’ll have a look at some of Sentinel’s main features. Further, we’ll see an example of how to use it, its annotation support, and its monitoring dashboard.
在本教程中,我们将看一下Sentinel的一些主要功能。此外,我们将看到一个如何使用它的例子,它的注释支持,以及它的监控仪表板。
2. Features
2.特点
2.1. Flow Control
2.1.流量控制
Sentinel controls the speed of random incoming requests to avoid the overloading of microservices. This ensures that our service isn’t killed by a surge in traffic. It supports a variety of traffic shaping strategies. These strategies automatically adjust traffic to appropriate shapes when Queries per Second (QPS) is too high.
Sentinel控制随机传入请求的速度,以避免微服务的过载。这确保我们的服务不会被激增的流量杀死。它支持各种流量整形策略。当每秒查询次数(QPS)过高时,这些策略会自动将流量调整为适当的形状。
Some of these traffic shaping strategies are:
这些流量整形策略中的一些是。
- Direct Rejection Mode – When the number of requests per second exceeds the set threshold, it’ll automatically reject further requests
- Slow Start Warm-Up Mode – If there’s a sudden surge in traffic, this mode ensures that the request count goes on increasing gradually, until reaching the upper limit
2.2. Circuit Breaking and Downgrade
2.2.断路和降级
When one service synchronously calls another, there’s a possibility that another service can be down for some reason. In such a case, threads are blocked as they keep on waiting for the other service to respond. This can lead to resource exhaustion and the caller service will also be unable to handle further requests. This is called a cascading effect and can take down our entire microservices architecture.
当一个服务同步调用另一个服务时,另一个服务有可能因为某种原因而停机。在这种情况下,线程会被阻塞,因为它们一直在等待其他服务的响应。这可能会导致资源耗尽,调用者服务也将无法处理进一步的请求。这被称为级联效应,可以使我们的整个微服务架构瘫痪。
To prevent such scenarios, a circuit breaker comes into the picture. It will block all subsequent calls to the other service immediately. After the timeout period, some requests are passed through. If they succeed, then the circuit breaker resumes normal flow. Otherwise, the timeout period starts again.
为了防止这种情况的发生,一个断路器就出现了。它将立即阻止对其他服务的所有后续调用。在超时期过后,一些请求会被通过。如果它们成功了,那么断路器就会恢复正常流动。否则,超时期又开始了。
Sentinel uses the principle of max concurrency limiting to implement circuit breaking. It reduces the impact of unstable resources by restricting the number of concurrent threads.
Sentinel使用最大并发限制的原则来实现断路。它通过限制并发线程的数量来减少不稳定资源的影响。
Sentinel also downgrades unstable resources. All calls to the resource will be rejected in the specified time window when the response time of a resource is too high. This prevents situations where calls become very slow, leading to the cascading effect.
哨兵也会将不稳定的资源降级。当一个资源的响应时间过高时,对该资源的所有调用将在指定的时间窗口被拒绝。这可以防止调用变得非常慢,导致级联效应的情况。
2.3. Adaptive System Protection
2.3.自适应系统保护
Sentinel protects our server in case the system load goes too high. It uses load1 (system load) as the metric to initiate traffic control. The request will be blocked under the following conditions:
Sentinel在系统负载过高的情况下保护我们的服务器。它使用load1(系统负载)作为衡量标准来启动流量控制。在下列情况下,请求将被阻止。
- Current system load (load1) > threshold (highestSystemLoad);
- Current concurrent requests (thread count) > estimated capacity (min response time * max QPS)
3. How to Use
3.如何使用
3.1. Add Maven Dependency
3.1.添加Maven依赖项
In our Maven project, we need to add the sentinel-core dependency in the pom.xml:
在我们的Maven项目中,我们需要在pom.xml中添加sentinel-core依赖。
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.0</version>
</dependency>
3.2. Define Resource
3.2.定义资源
Let’s define our resource with the corresponding business logic inside a try-catch block using the Sentinel API:
让我们在使用Sentinel API的try-catch 块中定义我们的资源和相应的业务逻辑。
try (Entry entry = SphU.entry("HelloWorld")) {
// Our business logic here.
System.out.println("hello world");
} catch (BlockException e) {
// Handle rejected request.
}
This try-catch block with the resource name “HelloWorld”, serves as the entry point to our business logic, guarded by Sentinel.
这个资源名称为 “HelloWorld “的try-catch块,是我们业务逻辑的入口,由Sentinel负责保护。
3.3. Define Flow Control Rules
3.3.定义流量控制规则
These rules control the flow to our resources, like threshold count or control behavior — for example, reject directly or slow startup. Let’s use FlowRuleManager.loadRules() to configure the flow rules:
这些规则控制流向我们的资源,如阈值计数或控制行为 – 例如,直接拒绝或缓慢启动。让我们使用FlowRuleManager.loadRules()来配置流量规则。
List<FlowRule> flowRules = new ArrayList<>();
FlowRule flowRule = new FlowRule();
flowRule.setResource(RESOURCE_NAME);
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
flowRule.setCount(1);
flowRules.add(flowRule);
FlowRuleManager.loadRules(flowRules);
This rule defines that our resource “RESOURCE_NAME” can respond to a maximum of one request per second.
这条规则定义了我们的资源 “RESOURCE_NAME “每秒钟最多可以响应一个请求。
3.4. Defining Degrade Rules
3.4.定义降级规则
Using degrade rules, we can configure the circuit breaker’s threshold request count, recovery timeout, and other settings.
Let’s configure the degrade rules using DegradeRuleManager.loadRules():
使用降级规则,我们可以配置断路器的阈值请求数、恢复超时和其他设置。
让我们使用DegradeRuleManager.loadRules()来配置降级规则。
List<DegradeRule> rules = new ArrayList<DegradeRule>();
DegradeRule rule = new DegradeRule();
rule.setResource(RESOURCE_NAME);
rule.setCount(10);
rule.setTimeWindow(10);
rules.add(rule);
DegradeRuleManager.loadRules(rules);
This rule specifies that when our resource RESOURCE_NAME fails to serve 10 requests (threshold count), the circuit will break. All subsequent requests to the resource will be blocked by Sentinel for 10 seconds (time window).
这条规则规定,当我们的资源RESOURCE_NAME未能提供10个请求(阈值计数)时,电路将中断。所有对该资源的后续请求将被Sentinel阻断10秒(时间窗口)。
3.5. Defining System Protection Rules
3.5.定义系统保护规则
Using system protection rules, we can configure and ensure adaptive system protection (threshold of load1, average response time, concurrent thread count). Let’s configure the system rules using the SystemRuleManager.loadRules() method:
使用系统保护规则,我们可以配置并确保自适应的系统保护(load1的阈值、平均响应时间、并发线程数)。让我们使用SystemRuleManager.loadRules()方法配置系统规则。
List<SystemRule> rules = new ArrayList<>();
SystemRule rule = new SystemRule();
rule.setHighestSystemLoad(10);
rules.add(rule);
SystemRuleManager.loadRules(rules);
This rule specifies that, for our system, the highest system load is 10 requests per second. All further requests will be blocked if the current load goes beyond this threshold.
这条规则规定,对于我们的系统,最高的系统负载是每秒10个请求。如果当前负载超过这个阈值,所有进一步的请求将被阻止。
4. Annotation Support
4.注释支持
Sentinel also provides aspect-oriented annotation support for defining the resource.
Sentinel还为定义资源提供了面向方面的注释支持。
First, we’ll add the Maven dependency for sentinel-annotation-aspectj:
首先,我们要添加sentinel-annotation-aspectj的Maven依赖项。
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>1.8.0</version>
</dependency>
Then, we add @Configuration to our configuration class to register the sentinel aspect as a Spring bean:
然后,我们在配置类中添加@Configuration,将哨兵方面注册为Spring Bean。
@Configuration
public class SentinelAspectConfiguration {
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
}
@SentinelResource indicates the resource definition. It has attributes like value, which defines the resource name. Attribute fallback is the fallback method name. When the circuit is broken, this fallback method defines the alternate flow of our program. Let’s define the resource using the @SentinelResource annotation:
@SentinelResource表示资源定义。它有像value这样的属性,它定义了资源名称。属性fallback是回退方法的名称。当电路中断时,这个回退方法定义了我们程序的备用流程。让我们使用@SentinelResourceannotation来定义资源。
@SentinelResource(value = "resource_name", fallback = "doFallback")
public String doSomething(long i) {
return "Hello " + i;
}
public String doFallback(long i, Throwable t) {
// Return fallback value.
return "fallback";
}
This defines the resource with the name resource_name, as well as the fallback method.
这定义了名称为resource_name的资源,以及回退方法。
5. Monitoring Dashboard
5.监测仪表板
Sentinel also provides a monitoring dashboard. With this, we can monitor the clients and configure the rules dynamically. We can see the amount of incoming traffic to our defined resources in real-time.
Sentinel还提供了一个监控仪表板。通过它,我们可以监控客户端并动态配置规则。我们可以实时看到进入我们定义的资源的流量。
5.1. Starting the Dashboard
5.1.启动仪表板
First, we need to download the Sentinel Dashboard jar. And then, we can start the dashboard using the command:
首先,我们需要下载Sentinel Dashboard jar>。然后,我们可以使用命令来启动仪表板。
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar
Once the dashboard application starts up, we can connect our application following the steps in the next sections.
一旦仪表盘应用程序启动,我们就可以按照下一节的步骤连接我们的应用程序。
5.2. Preparing Our Application
5.2.准备我们的应用程序
Let’s add the sentinel-transport-simple-http dependency to our pom.xml:
让我们把sentinel-transport-simple-http依赖性添加到我们的pom.xml。
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.8.0</version>
</dependency>
5.3. Connecting Our Application to the Dashboard
5.3.将我们的应用程序连接到仪表板上
When starting the application, we need to add the dashboard IP address:
在启动应用程序时,我们需要添加仪表板的IP地址。
-Dcsp.sentinel.dashboard.server=consoleIp:port
Now, whenever a resource is called, the dashboard will receive the heartbeat from our application:
现在,只要有资源被调用,仪表盘就会收到来自我们应用程序的心跳。
We can also manipulate the flow, degrade, and system rules dynamically using the dashboard.
我们还可以使用仪表板动态地操纵流量、降级和系统规则。
6. Conclusion
6.结语
In this article, we saw the main features of Alibaba Sentinel flow control, circuit breaker, and adaptive system protection.
在这篇文章中,我们看到了阿里巴巴Sentinel流量控制、断路器和自适应系统保护的主要特点。
Corresponding examples can be found over on GitHub.
相应的例子可以在GitHub上找到over。