Spring Cloud series_ 22 Sentinel defines resources and rules

Define resources

Resources are one of the core concepts of sentinel. Resources here can be anything, such as services, methods in services, and a piece of code. Sentinel provides @ SentinelResource to define resources and AspectJ extension to customize resources and handle blockexceptions

After adding @ SentinelResource to the resource, you can use the configuration file or console to control the flow and fuse of the resource

About parameters in @ SentinelResource

  • value: resource name, required
  • blockHandler / blockHandlerClass:blockHandler corresponds to the name of the function handling BlockException. In short, it is a method called when concurrent requests exceed a certain frequency. The range that blockHandler function needs to access is public, the return type needs to match the original method, the parameter type needs to match the original method, and finally add an additional parameter with the type of BlockException

blockHandler is the Class object of the corresponding Class by default. Note that the corresponding function must be static modifier, otherwise it cannot be parsed

  • Fallback: used to specify the processing logic when throwing an exception. In short, it is the method called when an exception occurs. Fallback handles all exceptions (except those excluded in exceptionsToIgnore). Signature and location requirements of fallback function:
  1. The return value type must be consistent with the return value type of the original function
  2. The method parameter list needs to be consistent with the original function, or an additional Throwable type can be used to receive the corresponding exception
  3. The fallback method needs to be in the same Class as the original method by default. If you want to use other types of methods, you can specify fallbackClass as the Class object of the corresponding Class. Note that the corresponding method must be static modified, otherwise it cannot be resolved

Here, use service-consumer-sentinel-rest-7060 as an example

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    RestTemplate restTemplate;

    @SentinelResource(value = "getProductList",blockHandler = "getProductListBlockHandler",fallback = "getProductListFallback")
    @Override
    public List<Product> getProductList() {
        System.out.println(Thread.currentThread().getName()+"---getProductList----");
        ResponseEntity<List<Product>> exchange = restTemplate.exchange(
                "http://service-provider-sentinel/provider/getProducts", HttpMethod.GET, null, new ParameterizedTypeReference<List<Product>>() {
                });
        return exchange.getBody();
    }

    public List<Product> getProductListBlockHandler(BlockException blockException){
        blockException.printStackTrace();
        return Arrays.asList(new Product(1L,"flow control-Data 01",1,new BigDecimal(100))
        ,new Product(2L,"flow control-Data 02",1,new BigDecimal(100)));

    }

    public List<Product> getProductListFallback(Throwable throwable){
        System.out.println("Exception:"+throwable);
        return Arrays.asList(new Product(1L,"Fuse degradation-Data 01",1,new BigDecimal(100))
                ,new Product(2L,"Fuse degradation-Data 02",1,new BigDecimal(100)));

    }
}

After restarting the service, access this resource and let the sentinel console load it. It is found that relevant resources appear

 

Define rules

All sentinel rules can be dynamically queried and modified in memory (console mode), and take effect immediately after modification. Sentinel also provides relevant API s to customize policies.

sentinel supports the following rules:

  1. flow control
  2. Fuse degradation
  3. System protection
  4. Source access control
  5. Hotspot parameters
  • flow control

Here, set the maximum resource access to 1 per second, then we can quickly call it twice and find it and go directly

getProductListBlockHandler()

Then the request slowly returns the normal data

  • Fuse degradation

Simulate an error message

@SentinelResource(value = "getProductList",blockHandler = "getProductListBlockHandler",fallback = "getProductListFallback")
    @Override
    public List<Product> getProductList() {
        System.out.println(Thread.currentThread().getName()+"---getProductList----");
        //Simulation error
        Integer.parseInt("11,11");
        ResponseEntity<List<Product>> exchange = restTemplate.exchange(
                "http://service-provider-sentinel/provider/getProducts", HttpMethod.GET, null, new ParameterizedTypeReference<List<Product>>() {
                });
        return exchange.getBody();
    }

Accessing this resource directly again will call

getProductListFallback()

Return fuse data

It can also be configured on the console

Generally, it is not configured on the console

 

Dynamic rule extension

Sentinelproperties internally provides a datasource of TreeMap type, which is used to configure data source information and support

  1. File configuration rules
  2. Nacos configuration rules
  3. Zookeeper configuration rules
  4. Apollo configuration rules
  5. Redis configuration rules

Take file configuration as an example

to configure

spring:
    cloud:
      sentinel:
          transport:
            port: 8719
            dashboard: 192.168.3.222:8080
          datasource:
              ds1:
                  #Open file configuration
                  file:
                      #File name
                      file: classpath:flowRile.json
                      #data type
                      data-type: json
                      rule-type: flow

Add flowrile. In the resources folder JSON, corresponding to com alibaba. csp. sentinel. slots. block. Attributes in ruleconstant

[
  {
    "resource": "getProductList",
    "count": 1,
    "grade": 1,
    "limitApp": "default",
    "strategy": 0,
    "controlBehavior": 0
  }
]
attributeexplainDefault value
resourceResource name, which is the object of flow restriction rules 
countCurrent limiting threshold 
gradeCurrent limiting threshold, value type, QPS mode (1), number of concurrent threads mode (0)QPS
limitAppCall source for flow controldefault does not distinguish between sources
strategyCall relationship current limiting policy: direct (0) Association (1) link (2)According to the resource itself (direct)
controlBehaviorFlow control effect (direct decision / queuing / slow start mode), does not support flow restriction according to the call relationshipDirect rejection
clusterModeCluster current limitingno

 

After restarting the service and accessing the resource initialization, you can see the rules configured in the file on the console

Keywords: Spring Cloud

Added by inrealtime on Thu, 10 Feb 2022 16:30:18 +0200