“This is my 40th day of participating in the First Challenge 2022. For more details: First Challenge 2022.”

I. Baidu Baike

Sentinel is a high-availability traffic protection component for distributed service architecture. It mainly takes traffic as the entry point and helps developers guarantee the stability of microservices from multiple dimensions such as traffic limiting, traffic shaping, fuse downgrading, system load protection and hotspot protection.

1. Sentinel characteristics

Rich application scenarios: Sentinel has undertaken the core scenarios of Alibaba’s double Eleven traffic drive in the past 10 years, such as SEC killing (i.e. burst traffic control within the range of system capacity), message peaking and valley filling, cluster flow control, real-time fusing of unavailable downstream applications, etc.

Complete real-time monitoring: Sentinel also provides real-time monitoring capabilities. From the console, you can see a summary of the performance of a single machine-by-second data, or even a cluster of less than 500 machines, for accessing the application. Extensive Open source ecosystem: Sentinel provides out-of-the-box integration modules with other open source frameworks/libraries, such as Spring Cloud, Dubbo, and gRPC. You can quickly access Sentinel by introducing the appropriate dependencies and simple configuration.

Sophisticated SPI extension points: Sentinel provides an easy-to-use, sophisticated SPI extension interface. You can quickly customize the logic by implementing an extension interface. For example, customize rule management and adapt dynamic data sources.

2. Sentinel’s open source ecosystem

History of Sentinel

Sentinel was born in 2012 and its main function is inlet flow control.

From 2013 to 2017, Sentinel developed rapidly within Alibaba Group and became a basic technology module, covering all core scenarios. Sentinel has thus accumulated a large number of traffic aggregation scenarios and production practices.

Sentinel became open source in 2018 and continues to evolve.

In 2019, Sentinel continued to explore multilingual extensions with the release of a C++ native version and Envoy cluster traffic control support for Service Mesh scenarios to address multilingual traffic limiting issues under the Service Mesh architecture.

In 2020, Sentinel Go was released, continuing its evolution toward cloud native.

Basic concept of Sentinel

1, resources,

Resources are the key concept of Sentinel. It can be anything in a Java application, for example, a service provided by the application, or another application invoked by the application, or even a piece of code. In the rest of the documentation, we will describe code blocks in terms of resources.

Any code defined through the Sentinel API is a resource that can be protected by Sentinel. In most cases, resources can be identified using method signatures, urls, and even service names as resource names.

2,

The rules set around the real-time status of resources can include flow control rules, fuse degrade rules, and system protection rules. All rules can be dynamically adjusted in real time.

4. Advantages of Sentinel

Friendly control panel Support real-time monitoring to support multiple current limiting, such as QPS current limit, the number of threads and a variety of current limiting strategy Supports a variety of degraded mode, according to the average return time degradation, degradation by number of a variety of abnormal, according to the proportion of abnormal degradation such as convenient extension development, support the SPI mode of chain extension Support link connection, It can realize traffic limiting by link statistics, system protection, hot resource protection and so on

5. Sentinel function and design concept

1. What is flow control

Flow control is a common concept in network transmission, which is used to adjust the sending data of network packets. However, from the perspective of system stability, there are also a lot of considerations on the speed of processing requests. Requests arriving at any time are often random and uncontrollable, and the processing capacity of the system is limited. We need to control the flow according to the processing capacity of the system. Sentinel, as a dispatcher, can adjust random requests to fit as needed, as shown in the following figure:

2. Flow control design concept

Flow control has the following angles:

Resource invocation relationship, such as resource invocation link, resource and resource relationship; Performance metrics, such as QPS, thread pool, system load, etc. Control effects, such as direct current limiting, cold start, queuing, etc. Sentinel is designed to give you the freedom to choose the Angle of control and combine it flexibly to achieve the desired effect.

3. What is circuit breaker downgrade

In addition to flow control, the timely fusing of unstable factors in the call link is also one of Sentinel’s missions. Due to the complexity of invocation relationships, if a resource in the invocation link is unstable, requests may pile up, leading to cascading errors.The principle of Sentinel and Hystrix is the same: when a resource is detected to be unstable in the invocation link, such as a long response time or a high proportion of exceptions, the invocation of this resource is restricted to make the request fail quickly and avoid the cascading failure of other resources.

Here is a reference to Hystrix from the elastic engineering work that the Netflix API team started in 2011. Hystrix grew and matured in 2012, and many teams within Netflix adopted it. Today, hundreds of billions of thread isolation and thousands of signal isolation calls are performed on Netflix every day, greatly improving runtime and resiliency.

4. Fuse downgrade design concept

Sentinel and Hystrix have taken radically different approaches to their limitations.

Hystrix isolates dependencies (corresponding to resources in the Sentinel concept) by means of thread pool isolation. The benefit of doing this is to achieve the most complete isolation between resources. The disadvantages are that in addition to the increased cost of thread switching (too many thread pools result in too many threads), the need to allocate thread pool sizes for individual resources up front, and this can be problematic for some scenarios that use ThreadLocal (such as Spring transactions).

Sentinel approaches this problem in two ways:

(1) Limit by the number of concurrent threads

Unlike the resource pool isolation approach, Sentinel reduces the impact of unstable resources on other resources by limiting the number of concurrent threads for resources. Not only is there no thread switching wastage, you don’t need to pre-allocate the size of the thread pool. When a resource is unstable, such as a long response time, the direct effect on the resource is a gradual accumulation of threads. When the number of threads accumulates to a certain number on a particular resource, new requests for that resource are rejected. The stacked thread completes its task before continuing to receive requests.

(2) Degrade resources for slow calls and exceptions

In addition to controlling the number of concurrent threads, Sentinel can quickly fuse unstable calls based on unstable factors such as response time and exceptions. When the response time of a dependent resource is too long, all access to the resource is denied until the specified time window has passed and the resource is gradually restored.

5. System adaptive protection

Sentinel also provides adaptive protection at the system dimension. Avalanche prevention is an important part of system protection. When system load is high, if you continue to let requests in, the system may crash and fail to respond. In a clustered environment, the network load balancer will forward the traffic that should be carried by this machine to other machines. If other machines are also in an edge state, the increased traffic will cause that machine to crash and the cluster to become unavailable.

Sentinel provides a protection mechanism to balance incoming traffic with the load of the system and ensure that the system can handle the most requests within its capacity.

6. How does Sentinel work

The main working mechanism of Sentinel is as follows:

Provide adaptive or display apis for mainstream frameworks to define resources that need to be protected, and provide facilities to perform real-time statistics on resources and call link analysis.

Traffic is controlled based on preset rules and real-time resource statistics. Sentinel also provides an open interface for defining and changing rules.

Sentinel provides a real-time monitoring system that allows you to quickly understand the current status of your system.

7. Comparison of competing products

Six, SpringBoot integration of Sentinel

1. Join POM

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>0.2.1. RELEASE</version>
</dependency>
Copy the code

2. Write Sentinel rules

@PostConstruct
public void initFlowRules(a){
    //1. Create a set of traffic limiting rules
    List<FlowRule> rules = new ArrayList<>();
    //2. Create a traffic limiting rule
    FlowRule rule = new FlowRule();
    // Define the resource that sentinel will apply to
    rule.setResource("helloSentinel");
    // Define the traffic limiting rule type
    rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    // Define the number of QPS requests that can pass per second
    rule.setCount(2);
    //3. Add the traffic limiting rule to the collection
    rules.add(rule);
    //4. Load the traffic limiting rule
    FlowRuleManager.loadRules(rules);
}
Copy the code
@GetMapping("/helloSentinel")
public String hello(a){
    try{
        Entry entry = SphU.entry("helloSentinel");
        return "helloSentinel success.";
    }catch (Exception e){
        log.error(e.getMessage());
        return "helloSentinel error"; }}Copy the code

3, test,

(1) If the frequency is less than 1 second, the access succeeds(2) When the frequency is greater than twice per second, it fails due to the establishment of the current limiting rule

7. Springboot integrates sentinel Dashboard

1. Install Sentinel Dashboard

(1) Download the JAR package

Sentinel-1.7.1 JAR package download link

Link: pan.baidu.com/s/1reC7C4sO…

Extraction code: 11GM

(2) Start the JAR package

java -Dserver.port=9000 -jar sentinel-dashboard.jar

2. Springboot integrates sentinel Dashboard

(1) Introduction of POM

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-transport-simple-http</artifactId>
    <version>1.7.2</version>
</dependency>
Copy the code

(2) Configure the startup class

-Dcsp.sentinel.dashboard.server=localhost:9000 -Dproject.name=GooReeyProject (3) Call the interface to make it displayed in Dashboard

3. Configure flow control with Sentinel Dashboard

(1) Comment out the flow control setting code in the code

(2) Replace code with console configuration

Other ways of defining resources in Sentinel

1. Define resources by throwing exceptions

@GetMapping("/helloSentinel")
public String hello(a){
    try{
        Entry entry = SphU.entry("helloSentinel");
        return "helloSentinel success.";
    }catch (Exception e){
        log.error(e.getMessage());
        return "helloSentinel error"; }}Copy the code

2. Define resources by returning Boolean values

Code examples:

@GetMapping("/sentinelBoolean")
public boolean sentinelBoolean(a){
    if(SphO.entry("sentinelBoolean")) {try {
            log.info("sentinelBoolean success.");
            return true;
        }finally{ SphO.exit(); }}else{
        log.warn("sentinelBoolean error.");
        return false; }}Copy the code

3. Sentinel supports statistics of asynchronous call links

In asynchronous calls, resources are defined through the sphu.asynventry (XXX) method, and exit() is usually called in the asynchronous callback function.

Code writing:

(1) Add the @enableAsync annotation to the start class

 
@EnableDiscoveryClient
@SpringBootApplication(scanBasePackages = "com.guor")
@MapperScan("com.guor.management.dao")
@RefreshScope
@EnableAsync
public class ManagementApplication {
 
    public static void main(String[] args) { SpringApplication.run(ManagementApplication.class, args); }}Copy the code

(3) Control layer

@GetMapping("/sentinelAsync")
public void sentinelAsync(a){
    AsyncEntry asyncEntry = null;
    try {
        asyncEntry = SphU.asyncEntry("sentinelAsync");
        userService.sentinelAsync();
        log.info("sentinelAsync success.");
    }catch (BlockException e){
        log.error("sentinelAsync error.");
    }finally {
        if(asyncEntry ! =null){ asyncEntry.exit(); }}}Copy the code

When Sentinel Dashboard is not defined:Sentinel Dashboard definition: Flow control success!

4. Annotation form defines resources

(1) POM file

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-annotation-aspectj</artifactId>
    <version>1.7.2</version>
</dependency>
Copy the code

(2) Configuration class

package com.guor.management.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
 
@Configuration
public class SentinelAspectConfig {
 
    @Bean
    public SentinelResourceAspect sentinelResourceAspect(a){
        return newSentinelResourceAspect(); }}Copy the code

(3) Control class

@SentinelResource(value = "sentinel_Annotation", blockHandler = "exceptionHandler")
@GetMapping("/annotation")
public String sentinelAnnotation(a){
    return "sentinelAnnotation";
}
 
public String exceptionHandler(BlockException e){
    e.printStackTrace();
    return "System busy, please wait.";
}
Copy the code

(4) Define flow control rules