4. SpringCloud: Sentinel service flow control and service degradation

Table of contents

1. Guide

2. Basic concepts of Sentinel

resource

rule

Three, Sentinel console

Four, Sentinel client (application)

5. Define flow control rules

6. Define resources

7. Hotspot rules

8. API access

9. Rule Persistence (Rule Center)

10. Using Sentinel in a production environment


1. Guide

        Sentinel, like Hystrix, is a concrete implementation of Spring Cloud Circuit Breaker (in fact, this statement is not rigorous, because Sentinel does not depend on Spring Cloud).

Sentinel supports functions such as service flow control and circuit breaker downgrade.

The use of Sentinel can be divided into two parts:

  • Core library (Java application client): does not depend on any framework/library, can run in the runtime environment of Java 8 and above, and also has good support for frameworks such as Dubbo / Spring Cloud (see mainstream framework  adaptation ) . is the real rule enforcer.
  • Console (Dashboard): Dashboard is mainly responsible for managing push rules, monitoring, and managing machine information. It is just a console (console is optional) and is not responsible for storing rules and flow control itself.

2. Basic concepts of Sentinel

resource

Resources are a key concept of Sentinel. It can be anything in a Java application, such as a service provided by the application, or a service provided by another application called by the application, or even a piece of code. In the following documents, we will use resources to describe code blocks.

As long as the code defined by Sentinel API is a resource, it can be protected by Sentinel. In most cases, you can use method signatures, URLs, or even service names as resource names to identify resources.

rule

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

3. Sentinel Console Dashboard

Sentinel provides a lightweight open source console that provides machine discovery and health management, monitoring (single machine and cluster), rule management and push functions. ( The specific execution of traffic control and service degradation rules is still Sentinel in the application, not the console )

Sentinel console includes the following functions:

  • Check the machine list and health status : collect the heartbeat packets sent by the Sentinel client to determine whether the machine is online.
  • Monitoring (stand-alone and cluster aggregation) : Through the monitoring API exposed by the Sentinel client, the application monitoring information is periodically pulled and aggregated, and finally real-time monitoring at the second level can be achieved.
  • Rule management and push : unified management push rules (but do not store rules, do not execute rules).
  • Authentication : Authentication is very important in the production environment. Here each developer needs to customize according to their actual situation.

   1. Download: https://github.com/alibaba/Sentinel/releases

   2. Run:

java -Dserver.port=8383 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.2.jar

Which  -Dserver.port=8383 is used to specify the Sentinel console listening port as 8383 

 3、启动后浏览器访问:http://IP:端口   (用户名密码默认都是sentinel)

 Applications are not yet visible here. Because there is no application reporting the situation to Sentinel at this time.

Four, Sentinel client (application)

Sentinel itself is an independent component and may not be bound to Spring Cloud. However, since Spring Cloud is used a lot, Spring is also used here as an example.

Based on the previous project (based on this project   https://blog.csdn.net/zyplanke/article/details/120860958  ).

1. Increase sentinel dependency

  ------ 省略 ------
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>${springcloudalibaba.version}</version>
        </dependency>
  ------ 省略 ------

2. Increase the interconnection parameters between the application and the console.

[Method 1]: Add two JVM parameters when Java starts

-Dcsp.sentinel.dashboard.server=IP:8383
-Dcsp.sentinel.api.port=8719 

The first JVM parameter is: Sentinel console address, the application (client) will automatically send a heartbeat packet to the console address.

The second JVM parameter is: the HTTP port that the application (client) starts locally (the default starting port is 8719, if the port is already occupied, it will be automatically incremented until a free port is found), and the Sentinel console will access this Port (for example, when the console adds a rule, it will push the rule to the application through this port).

[Method 2]: Pass parameters in Spring's application.properties configuration file (or configuration center):

spring.cloud.sentinel.transport.dashboard and spring.cloud.sentinel.transport.port configuration specification (method 1 and method 2, the two configuration effects are equivalent)

Note: Make sure that the network between the application and the Sentinel console is unobstructed.

3. View the situation through the console

It is necessary to ensure that the application (client) has traffic. The application needs at least 1 access to complete Sentinel initialization (so that it can be seen in the Sentinel console)

5. Define flow control rules

In the Sentinel console, add a traffic rule for the payment service, as follows:

Note: If the QPS threshold is 0, it is equivalent to treating all failures.

After the rules are defined in the console, the rules will be automatically transferred to the application (here, the payment application).

The storage and execution of the rules are all completed on the application side. The console only receives reports from the application and does not store the rules itself (only scratched in memory).

At this time, when payment is called, sentinel will execute this flow control rule. Those that exceed this rule will return failure according to the rule definition.

The denied access can be seen in the caller log: " Blocked by Sentinel (flow limiting) "

For the parameter configuration and meaning of each rule, please refer to the official website: https://sentinelguard.io/zh-cn/docs/introduction.html

6. Define resources

 Sentinel takes the exposed HTTP service as a resource by default, and we sometimes need to define resources ourselves. (such as defining a function as a resource). The way to define resources is as follows:

1. In Spring,  SentinelResourceAspect register as a Spring Bean through Java Config. Add a function in the main SpringBoot (take payment as an example)

@SpringBootApplication
@EnableDiscoveryClient
public class PaymentApplication {

    public static void main(String[] args) {
        SpringApplication.run(PaymentApplication.class, args);
    }
    
    @Bean  // 将SentinelResourceAspect 注册为Bean,以支持@SentinelResource注解
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
}

2. Use the @SentinelResource annotation to define a function as a resource where needed. For example:

@RestController
public class PaymentController {
    @Value("${server.port}")
    private int myport;

    @GetMapping("/dopay/{orderid}")
    @SentinelResource(value = "resourcePayPPP", entryType = EntryType.IN, fallback = "fallbackHandler")
    public ResponseEntity<String> paylogic(@PathVariable("orderid") Long orderid) {
        return ResponseEntity.ok("支付服务successful! orderid=" + orderid + ", 支付成功。 支付服务的端口为port=" + myport );
    }

    /**
     * 服务降级的处理函数,需要与原函数的返回类型、入参保持一致(入参最后需要增加一个BlockException)
     */
    public ResponseEntity<String> fallbackHandler (Long orderid, BlockException e) {
        System.err.println("fallbackHandler 限流,当前系统忙");
        return ResponseEntity.ok("限流,当前系统忙");
    }
}

Among them: @SentinelResource(value = "resourcePayPPP", entryType = EntryType.IN, fallback = "fallbackHandler") respectively specify: resource name, IN or OUT, downgraded function name.

3. After startup (traffic needs to exist), you can check the resource status of the application in the " Cluster Link " menu interface in the console (as follows). Then you can set the rules for the resource name (see the operation on the console for details).

7. Hotspot rules

What is a hotspot? Hotspots are frequently accessed data. Many times we want to count the Top N data with the highest access frequency in a certain hotspot data, and restrict their access. for example:

  • Commodity ID is a parameter, count and limit the most frequently purchased commodity IDs within a period of time
  • The user ID is a parameter, which is restricted for user IDs that frequently access within a period of time

Hotspot parameter current limiting will count the hotspot parameters in the incoming parameters, and limit the resource calls containing hotspot parameters according to the configured current limiting threshold and mode. Hotspot parameter current limiting can be regarded as a special flow control, which only takes effect for resource calls containing hotspot parameters.

 1. Add hotspot rules

In the picture above:

  • Current limiting mode: only QPS
  • The parameter index is treeed from left to right from the input parameters of the resource function, the first is 0, and the second is 1. . .
  • Stand-alone threshold: current limiting QPS threshold
  • Statistical window length: the time window for threshold statistics.

2. After the rule is added, if the input parameter value is different for each call, the hotspot rule will not be triggered. If a large number of input parameters are passed in each time within a certain period of time are the same (for example, the same time class, calling and accessing with the same input parameter value), a hotspot will form and trigger hotspot current limiting.

 HTTP requests can be simulated by tools such as Jmeter

 

8. API access

The existing rules of the application (client)  can be obtained through the following API , and the rule data is returned in the form of a JSON array (the following are the IP and port of the client, not the IP of the Sentinel console).

# 获取应用程序的 流控规则
curl http://应用程序ip:sentinel端口/getRules?type=flow

# 获取应用程序的 服务熔断降级规则
curl http://应用程序ip:sentinel端口/getRules?type=degrade 

# 获取应用程序的 系统保护规则
curl http://应用程序ip:sentinel端口/getRules?type=system

# 获取应用程序的 某个资源的统计信息
curl http://应用程序ip:sentinel端口/cnode?id=resourceName

9. Rule Persistence (Rule Center)

Since Sentinel saves the rules in the memory of the application by default, the rule data will be lost after restarting the application. Therefore, it is necessary to persist the flow control and degradation rules in external data sources (such as files, databases, Nacos, etc.), so that the rules are read from the external data sources when the application starts.

  Here we take Nacos as an example ( https://blog.csdn.net/zyplanke/article/details/120860958 is demonstrated based on this project ).

1. With Nacos configuration center as Sentinel's external data source, it is necessary to add dependencies to the application

  ------ 省略 ------
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>${springcloudalibaba.version}</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
            <version>1.8.0</version>
        </dependency>
  ------ 省略 ------

2. Since the application has already used Nacos as the configuration center, add Sentinel external data source configuration in the content of the application configuration Data ID=paymentService.properties on Nacos, the content is as follows

# 指定Sentinel控制台的IP和端口
#spring.cloud.sentinel.transport.dashboard=ip:port

#配置Sentinel规则中心来源(持久化存放在Nacos配置中心)
spring.cloud.sentinel.datasource.ds1.nacos.rule-type=flow
spring.cloud.sentinel.datasource.ds1.nacos.server-addr=39.100.80.168:8848
spring.cloud.sentinel.datasource.ds1.nacos.data-id=sentinel_rules_flow.json
spring.cloud.sentinel.datasource.ds1.nacos.group-id=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds1.nacos.data-type=json

3. Add the Data ID configuration (corresponding to the configuration in the previous step) in the Nacos configuration center, where the JSON rules are as follows.

 Note that the JSON content has square brackets ( you can refer to the JSON content obtained by accessing the API through curl as a reference  )

[
    {
        "resource": "/dopay/{orderid}", 
        "limitApp": "default", 
        "grade": 1, 
        "count": 1, 
        "controlBehavior": 0, 
        "strategy": 0, 
        "clusterMode": false
    }
]

 4. Restart the application (after startup, at least 1 flow is required).

 5. Test verification. This is a test to find that the flow control rule has taken effect, and this flow control rule can also be seen in the Sentinel console

Process: The client application obtains the rules from the Nacos configuration center and applies them to the application. Later, the client application will actively report to the Sentinel console, so the Sentinel console interface can also see the rule

10. Using Sentinel in a production environment

See below for details:

https://github.com/alibaba/Sentinel/wiki/%E5%9C%A8%E7%94%9F%E4%BA%A7%E7%8E%AF%E5%A2%83%E4%B8%AD%E4%BD%BF%E7%94%A8-Sentinel

Guess you like

Origin blog.csdn.net/zyplanke/article/details/120980633