sentinel learning document

Posted by Byron on Mon, 27 Dec 2021 17:07:06 +0100

sentinel documents summarized in the internship

Official documents: https://sentinelguard.io/zh-cn/docs/dashboard.html

1. Characteristics

Sentinel vs. Hystrix

SentinelHystrix
Isolation strategyBased on ConcurrencyThread pool isolation / semaphore isolation
Fuse degradation strategyBased on response time or failure rateBased on failure ratio
Real time index realizationsliding windowSliding window (based on RxJava)
Rule configurationSupport multiple data sourcesSupport multiple data sources
ExpansibilityMultiple extension pointsForm of plug-in
Annotation based supportComing soonsupport
Call link informationSupport synchronous callI won't support it
Current limitingBased on QPS / concurrency number, current limiting based on call relationship is supportedI won't support it
Flow shapingSupport slow start and homogenizer modeI won't support it
System load protectionsupportI won't support it
Real time monitoring APIevery kind ofRelatively simple
ConsoleOut of the box, you can configure rules, view second level monitoring, machine discovery, etcimperfect
Adaptation of common framesServlet, Spring Cloud, Dubbo, gRPC, etcServlet,Spring Cloud Netflix

2. Download and use

Download sentinel console jar package address: https://ithub.com/alibaba/Sentinel/releases

Start sentinel through java -jar. The default port occupied by sentinel is 8080. If there is a need to change the port, change the corresponding port. Change here to 18080.

Start the command line in the jar package directory and run:

java -Dserver.port=18080 -jar  sentinel-dashboard-1.8.0.jar 

Visit localhost: 18080 to open the local console.

From sentinel 1.6 Since 0, sentinel console has introduced basic login function. The default user name and password are sentinel.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-xW7vtiQM-1628843889144)(sentinel demo document. assets/1628071038326.png)]

3. Basic configuration

Join dependency management and dependency

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-dependencies</artifactId>
			<version>Hoxton.SR8</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>

		<!--springCloud-Alibaba-->
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-alibaba-dependencies</artifactId>
			<version>2.2.1.RELEASE</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>

		<!--sentinel Current limiting-->
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
			<version>2.2.1.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
			<version>2.2.2.RELEASE</version>
		</dependency>
	</dependencies>

Note that you can modify the port and other corresponding information. Here sentinel uses the self-defined 18080 port

server:
    port: 8080
spring:
    application:
      name: sentinel-demo
    cloud:
      sentinel:
        transport:
          dashboard: 127.0.0.1:18080
        eager: true
        datasource:
          ds1:
            file:
              file: classpath:flowrule.json
              data-type: json
              rule-type: flow
          ds2:
            file:
              file: classpath:degraderule.json
              data-type: json
              rule-type: degrade

Startup class

@SpringBootApplication
public class SentinelMainApplication {

	public static void main(String[] args) {
		SpringApplication.run(SentinelMainApplication.class, args);
	}

}

Controller class requiring flow control, sample code

@RestController
public class DemoController {
   
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/resource")
    @SentinelResource(value = "test-resource", blockHandlerClass = {ExceptionUtil.class}, blockHandler = "exHandler")
    public String resource() {
        return "resource";
    }
}  

Startup class

It should be noted that sentinel is a lazy loading mechanism, which also means that you need to access some / hello in the above Controller to see the service in the sentinel background
Browser access http://localhost:8080//hello

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-3jmhkx1-1628843889147) (sentinel demo document. assets/1628147140825.png)]

Then refresh the sentinel background http://localhost:18080/#/dashboard/home

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-dloDbuwH-1628843889148)(sentinel demo document. assets/1628128462977.png)]

Monitoring of / hello has occurred.

4. Project structure

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-cWy7FtzQ-1628843889151)(sentinel demo document. assets/1628242834923.png)]

1.DemoController.java: used to test url flow restriction, association mode and flow restriction by resource name

2.ConfigDemoController.java: test file mode rule persistence

3.DegradeController: fuse degradation test

4.ParamController.java,SecurityController.java: black and white list function test

5.DemoUrlBlockHandler.java: intercept information customization

6.ExceptionUtil.java: prompt method collection class for intercepting resource requests

7.flowrule.json: store local flow control rules

8.sentinel-dashboard-1.8.0.jar: sentinel console jar package.

5. Flow control

Direct mode

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-IQWtgVwN-1628843889153)(sentinel demo document. assets/1628144441765.png)]

Add a flow control rule to control the flow of / hello port, and set the maximum access times per second 2; The default mode here is direct mode, quick failure, and advanced options are selected for other modes.

Quickly visit / hello to see the results.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-TlYGSSGw-1628843889155)(sentinel demo document. assets/1628144763772.png)]

The default interception information of the system can also be customized:

Create demourlblockhandler. config package java

@Component
public class DemoUrlBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletResponse.getWriter().println("flow is limiting");
    }
}

Association mode

Add a flow control rule and open advanced options:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-xnwm5ly-1628843889156) (sentinel demo document. assets/1628146026738.png)]

Add DemoController under Controller package:

 @GetMapping("/helloA")
    public String helloA() {
        return "helloA";
    }

Test:

Use postman to simulate the dense access / helloA interface, set 20 threads to access every 0.3 seconds.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-cQk90xHM-1628843889157)(sentinel demo document. assets/1628146750174.png)]

View the related resources: / hello.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-4DZ40h00-1628843889158)(sentinel demo document. assets/1628146940863.png)]

Note: when the QPS threshold of the associated resource / hello a exceeds 1, access to / hello is restricted.

Link mode

1. Under the cluster node link, view that the resource entry of / hello is sentinel_spring_web_context ;

2. Add flow control and configure the link entry resource as sentinel_web_servlet_context ;

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-1wySdvzA-1628843889159)(sentinel demo document. assets/1628148057148.png)]

3. When frequently accessing the interface / hello, an error flow is limiting is found, indicating that the flow is limited.

Limit current by resource name

@SentinelResource annotation: it is used to define resources and provides AspectJ extension for automatically defining resources and handling blockexceptions;

Add the following code to DemoController:

 @GetMapping("/resource")
 @SentinelResource(value = "test-resource", blockHandlerClass = {ExceptionUtil.class}, blockHandler = "exHandler")
    public String resource() {
        return "resource";
    }

Define resource name: Test Resource

Add flow control rule by resource name:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-2LL5edzW-1628843889160)(sentinel demo document. assets/1628156027540.png)]

Quick access / resource:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ZhkvQlyY-1628843889161)(sentinel demo document. assets/1628156111731.png)]

6. Rule persistence

Once we restart the application, Sentinel rules will disappear, and the production environment needs to persist the configuration rules.

Local file persistence rules are used here.

1. Add yml configuration:

 datasource:
          ds1:
            file:
              file: classpath:flowrule.json
              data-type: json
              rule-type: flow

2. Create a new json saving rule with the same name under resource:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-u5wYhF4F-1628843889162)(sentinel demo document. assets/1628215679503.png)]

3. Write rules:

[
  {
    "resource": "file-resource",
    "controlBehavior": 0,
    "count": 1,
    "grade": 1,
    "limitApp": "default",
    "strategy": 0
  },
  {
    "resource": "test-resource",
    "controlBehavior": 0,
    "count": 1,
    "grade": 1,
    "limitApp": "default",
    "strategy": 0
  }
]
  • Resource: resource name, that is, the object of the flow restriction rule
  • count: current limiting threshold
  • grade: current limiting threshold type (QPS or number of concurrent threads)
  • limitApp: the call source of flow control. If it is default, the call source will not be distinguished
  • Strategy: call relationship flow limiting strategy
  • controlBehavior: flow control effect (direct rejection, Warm Up, uniform queuing)

4. Start the service. Open the console.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-jUt0xmV3-1628843889163)(sentinel demo document. assets/1628215759988.png)]

7. Fuse degradation

Create a DegradeController and test it when an exception is generated.

public class DegradeController {
    int i=0;
    @GetMapping("/testD")
    public String message1() {
        i++;
        // The abnormal ratio is 0.333
        if (i % 3 == 0) {
            throw new RuntimeException("Simulation anomaly");
        }
        return "degrade is testing";
    }

New downgrade rule:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-95ObZqvl-1628843889163)(sentinel demo document. assets/1628237532280.png)]

When the exception ratio is greater than 0.25, the request per second is greater than or equal to 1; The degradation rule takes effect, the fuse duration is 10 seconds, and it returns to normal after 10 seconds.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-NzCl9c70-1628843889164)(sentinel demo document. assets/1628237689067.png)]

Fuse comparison with Hystrix:

The thread pool isolation commonly used by Hystrix will cause a large overhead of thread up and down switching; The semaphore isolation used by Hystrix controls the concurrency of a resource call. The effect is good, but it cannot automatically degrade slow calls;

Sentinel provides semaphore isolation through the flow control of the number of concurrent threads; In addition, sentinel supports more fuse degradation dimensions, can flow control and fuse a variety of indicators, and provides real-time monitoring and control panel, which is more powerful.

}
New downgrade rule:

[External chain picture transfer...(img-95ObZqvl-1628843889163)]

When the abnormal proportion is greater than 0.25,Requests greater than or equal to 1 per second; The degradation rule takes effect, and the fusing time is 10 seconds,10 Return to normal in seconds.

[External chain picture transfer...(img-NzCl9c70-1628843889164)]

**And Hystrix Fusing comparison of:**

Hystrix Common thread pool isolation will cause threads to switch up and down overhead Relatively large; Hystrix The semaphore isolation is used to control the concurrency of a resource call. The effect is good, but the slow call cannot be automatically degraded;

Sentinel The function of semaphore isolation is provided through the flow control of the number of concurrent threads; In addition, Sentinel It supports more fuse degradation dimensions, can flow control and fuse a variety of indicators, and provides real-time monitoring and control panel, which is more powerful.

Topics: Java Spring Spring Cloud