Hi, I am empty night ~

The sample code for this article is available at github.com/laolunsi/sp…


Download the Sentinel JAR package: github.com/alibaba/Sen…

Run java-jar sentinel-xx.jar, open a browser, and enter the default address: http://localhost:8080

Reference: How to use Sentinel? — Official documents

The flow control process of Sentinel is as follows:

  • Define the resources
  • Define the rules
  • Verify that the rules are in effect

concept

Resource, one of the core concepts of Sentinel, can be simply understood as a piece of code.

Sentinel ADAPTS to all mainstream frameworks. The following takes Spring Cloud as an example to record how sentinel is used for flow control in Spring Cloud micro-service architecture.

resources

It can be divided into the following ways:

  • The default configuration for mainstream frameworks
  • Throw an exception to define a resource
  • Returns a boolean-defined resource
  • Annotations define resources
  • Asynchronous invocation support

Annotated resources are used to control traffic on interfaces. The @resourcesentinel annotation is used. This annotation provides optional exception handling and fallback configuration items. Reference: Sentinel annotation support

Source:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface SentinelResource {
    // The resource name cannot be empty
    String value(a) default "";

    EntryType entryType(a) default EntryType.OUT;

    int resourceType(a) default 0;

    // Optional, function name to handle BlockException, default in this class; If you want to specify functions in other classes, you need to use the blockHandlerClass attribute
    String blockHandler(a) default ""; Class<? >[] blockHandlerClass()default {};

    // Optional fallback function name, used to provide fallback handling logic when an exception is thrown. You can target all types of exceptions. With the fallbackClass attribute, you can specify functions in other classes
    String fallback(a) default "";

    String defaultFallback(a) default ""; Class<? >[] fallbackClass()default {};

    Class<? extends Throwable>[] exceptionsToTrace() default {Throwable.class};

    // Ignore exceptions, that is, exceptions where fallback and blockHandler functions do not work
    Class<? extends Throwable>[] exceptionsToIgnore() default {};
}
Copy the code

Note:

  • The functions specified by blockHandler and fallback are in this class by default. The return value type and parameter order of this function must be the same as that of the original method. BlockHandler functions can add a BlockException parameter at the end, and fallback functions can add a Throwable parameter at the end
  • Use the corresponding blockHandlerClass and fallbackClass to specify the class of the corresponding function, rather than the default current class. Note that at this point, the specified function needs to be static, otherwise it cannot be parsed.

The rules

  • Flow control rule FlowRule: Flow control

The principle is to monitor indicators such as QPS or concurrent threads of application traffic and set thresholds to prevent services from being overwhelmed by instantaneous peak traffic. The purpose is to ensure high availability of applications during peak traffic.

  • It degrades to a normal temperature. Fuse DegradeRule: fuse degrade

The purpose is to prevent the avalanche caused by the unavailability of a single service, and it is also one of the methods to ensure the high availability of applications.

For unstable resources in the call link.

  • System protection rule SystemRule: adaptive traffic limiting

System protection rules control the incoming traffic at the application level (rather than the resource dimension), and monitor application indicators from several dimensions, such as load per machine, CPU usage, average RT, incoming QPS and concurrent threads, so that the system can run at the maximum throughput while ensuring the overall stability of the system.

  • Source access control rule AuthorityRule: Blacklist and whitelist control

Determine whether the request is allowed to pass based on the source of the call.

  • Hotspot parameter rule ParamFlowRule: traffic limiting of hotspot parameters

As a special flow control rule, it only applies to resource calls that contain hotspot parameters. Based on the hotspot parameters in the incoming parameters, the traffic limiting threshold and mode are configured, the resource invocation with hotspot parameters is restricted.

Sentinel also provides apis for customizing its own rules policies.

The default rule classification above can be defined in code or using Dashboard.

Rules can be defined using dashboards or created using code. If you want to persist rules, you can leverage a data source such as Nacos. We’ll talk about that later.


Spring Cloud integrates Sentinel

Reference: spring — cloud – alibaba – sentinel

Create a demo service to introduce sentinel dependencies in Spring-Cloud:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>. 0.9.0 RELEASE</version>
        </dependency>
Copy the code

Configuration:

server:
  port: 8203
spring:
  application:
    name: demo
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8081
Copy the code

You can configure flow control, degrade, hotspot, and authorization rules:

Annotation support Usage Reference: Annotation support – official documentation

By default, urls are used as link addresses and resource names. You can use the @SentinelResource annotation in your code to actively note the name of the resource, how to handle blocking, etc. Such as:

@RestController
@RequestMapping(value = "test")
@Validated
public class TestAction {

    private static Logger logger = LoggerFactory.getLogger(TestAction.class);

    @SentinelResource(value = "helloTest", blockHandler = "handleEx")
    @GetMapping(value = "hello")
    public String hello(@RequestParam("msg") @NotBlank String msg) {
        logger.info("hellow, " + msg);
        return "hello, " + msg;
    }

    @GetMapping(value = "send")
    @SentinelResource(value = "sendTest", blockHandler = "handleException", blockHandlerClass = BlockHandlerConfig.class)
    public String send(@NotBlank(message = "{required}") String email, @Email(message = "{invalid}") String msg) {
        return "Send a message to: + email + ", message content:" + msg;
    }

    public String handleEx(String msg, BlockException ex) {
        System.out.println(System error: MSG =" + msg + ", ex: " + ex);
        return "Traffic restriction, please try again later."; }}Copy the code

The helloTest here uses the handleEx method from this class as the blocking method. SendTest uses the handleException method from the BlockHandlerConfig class:

public class BlockHandlerConfig {

    public static String handleException(String email, String msg, BlockException exception) {
        return "444," + exception.getClass().getCanonicalName() + "\t service unavailable"; }}Copy the code

Note that the parameters of the method corresponding to blockHandle must be consistent with those of the resource; otherwise, the rule does not take effect and exceptions are thrown.

Configure a simple flow control for the helloTest resource:

Testing:

The interface corresponding to the quick request helloTest found that the success request interlaced with the limiting response. This indicates that our flow limiting rules and blockHandler are in effect.


Rule persistence

Note that these rule configurations will be lost if the service is restarted. One solution is to use Nacos as a configuration hub, where rule definitions are stored first.

Sentinel provides file/ NACOS/ZP/Apollo rule extension storage methods. For details, see the official document: Dynamic Rule Extension

In order for a service to use the configuration in Nacos as sentinel rules, in addition to Nacos dependencies, the following dependencies need to be introduced:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>. 0.9.0 RELEASE</version>
        </dependency>

                <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
            <version>1.8.0 comes with</version>
        </dependency>

        <! - to solve the problem under Caused by: Java. Lang. ClassNotFoundException: com.alibaba.csp.sentinel.log.Com mandCenterLog introduction -- -- >
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-transport-simple-http</artifactId>
            <version>1.8.0 comes with</version>
        </dependency>
Copy the code

Configuration:

spring:
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      datasource:
        ds1:
          nacos:
            server-addr: localhost:8848
            dataId: sentinel-config
            groupId: DEFAULT_GROUP
            data-type: json
            rule-type: flow
Copy the code

Create a new sentinel-config configuration file in nacos with the type JSON and the contents such as:

[{"resource": "helloTest"."limitApp": "default"."grade":   1."count":   3."strategy": 0."controlBehavior": 0."clusterMode": false}]Copy the code

When started, you can see that this rule appears in Sentinel. Change this rule in NACOS and find sentinel synchronized (not vice versa)


FAQ — Questions about the Sentinel deployment path

A previous issue with Sentinel deployment was this: I configured a domain name for microservice platforms, and each template, such as Gateway, Zipkin, and Sentinel, is accessed using nginx-configured request formats such as xxx.com/gateway/xxx.

When you open xxx.com/sentinel, you can see Dashboard and each service, but when you click on the service, you find that the monitoring data is missing, and the QPS of each address in the cluster point link is 0. When you click on the new flow control rule, the console reports a 404 exception.

I raised this issue in the official warehouse, and a brother named Jasonjoo2010 gave me a solution:

The static dashboard does not support arbitrary subdirectory deployment. You are advised to deploy the dashboard using an independent domain name.

Then I added a second level domain name just to access Sentinel, and that was it.

A detailed description of the problem is available at the Sentinel official repository: github.com/alibaba/Sen…


Reference:

  • What is Sentinel? — Official documents
  • Beginner’s Guide – Official documentation
  • Blog.csdn.net/xiongxianze…
  • Blog.csdn.net/weixin_4475…

I have been studying Redis, RabbitMQ, ES and other technologies in a systematic way recently, focusing on principles, underlying, concurrency and other issues. Welcome to our public account: JavaApes