Application practice of 06 sentinel current limiting fuse

catalogue

Sentinel introduction

Background analysis

Sentinel overview

Installing Sentinel services

Access Sentinal services

Sentinel current limiting primer

summary

Preparatory work

Sentinel current limiting introduction practice

Section interview analysis

Sentinel flow control rule analysis

Threshold type

Set current limiting mode

Section interview analysis

Sentinel downgrade application practice

summary

preparation

Sentinel demotion getting started

Sentinel exception handling

Section interview analysis

Sentinel hotspot rule analysis (key)

summary

quick get start

Specific parameter design

Section interview analysis

Sentinel system rules (understand)

summary

Section interview analysis

Sentinel authorization rules (important)

summary

quick get start

Section interview analysis

Summary

Analysis of key and difficult points

FAQ analysis

Bug analysis

Core knowledge points

Analysis of common problems

Common Bug analysis

Exercise 1 (customized handling of sentinel current limit exception based on business)

Exercise 2

Sentinel introduction

Background analysis

In our daily life, we often participate in the second kill, rush purchase and some preferential activities of goods on platforms such as Taobao, tmall, jd.com and pinduoduo. We also use 12306 mobile APP to grab train tickets and high-speed rail tickets on holidays. Sometimes we even help colleagues and friends to vote and brush tickets for their children, Without exception, these scenarios will cause a surge in server traffic, resulting in the inability to display web pages, slow APP response, abnormal function, and even the collapse of the whole website.
How can we ensure the safe operation of various businesses and the system will not collapse under any circumstances when these business flows are changeable? When the system load is too high, we can use three measures to protect the system: current limiting, degradation and fusing, which led to the birth of some flow control middleware. For example, Sentinel.
 

Sentinel overview

Sentinel (traffic guard of distributed system) is an open source comprehensive solution for service fault tolerance. Taking traffic as the starting point, it protects the stability of service from multiple dimensions such as traffic control, fuse degradation and system load protection.
Sentinel has undertaken the core scenarios of Alibaba's double 11 traffic promotion in recent 10 years, such as spike (i.e. burst traffic control within the range of system capacity), message peak cutting and valley filling, cluster traffic control, real-time fusing downstream unavailable applications, etc.

Sentinel core is divided into two parts:

  • Core library (Java client): it can run in all Java runtime environments, and also has good support for frameworks such as Dubbo /Spring Cloud.
  • Dashboard: it is developed based on Spring Boot and can be run directly after packaging.

Installing Sentinel services

Sentinel provides a lightweight console, which provides functions such as machine discovery, single machine resource real-time monitoring and rule management. The installation steps of the console are as follows:
Step 1: open sentinel download website

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

Step 2: download the Jar package (which can be stored in a sentinel directory), as shown in the figure:

Step 3: in the corresponding directory of sentinel, open the command line (cmd) and start and run sentinel

java -Dserver.port=8180 -Dcsp.sentinel.dashboard.server=localhost:8180 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.1.jar

Check the startup process, as shown in the figure:

Access Sentinal services

Step 1: if Sentinal starts ok, conduct access test through the browser, as shown in the figure:

Step 2: log in to sentinel. The default user and password are sentinel. The interface after successful login is shown in the figure:

Sentinel current limiting primer

summary

The database connection pool, thread pool and instantaneous concurrency of nginx in our system will be given a limited value when used, which itself is a flow limiting design. The purpose of flow restriction is to prevent malicious request traffic, malicious attacks, or prevent the traffic from exceeding the system peak.

Preparatory work

 

Step 1: Sentinel is applied to the service provider (SCA provider). Add dependencies on the service provider as follows:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>


Step 2: open the service provider configuration file bootstrap YML, add sentinel configuration, and the code is as follows:

spring:
  cloud:
    sentinel:
      transport:
         dashboard: localhost:8180 # Specify the sentinel console address.


Step 3: create a Controller object to demonstrate the current limiting operation, for example:

package com.jt.provider.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/provider")
public class ProviderSentinelController {
       @GetMapping("/sentinel01")
       public String doSentinel01(){
           return "sentinel 01 test  ...";
       }
}


Step 3: start the SCA provider service, and then access the specified service, as shown in the figure:

 

 

Step 4: refresh sentinel console to monitor information in real time, as shown in the figure:


Sentinel console is actually a program written by SpringBoot. We need to register our service on the console, that is, specify the address of the console in the micro service, and open a port on the consumer side to transfer data with sentinel console. The control console can call the monitoring program in the micro service through this port to obtain various information.

Sentinel current limiting introduction practice

Let's set the flow control (flow control) of the specified interface. The single machine threshold of QPS (requests per second) is 1, which means that the requests per second cannot exceed 1. Otherwise, we will limit the flow, and the direct call of the processing method fails.

Step 1: select the link to be current limited, as shown in the figure:

Step 2: set the current limiting strategy, as shown in the figure:

Step 3: repeatedly refresh and access the consumer service to detect whether the limited flow information is output, as shown in the figure:

Section interview analysis

  • What is Sentinel? (Alibaba has launched a flow control platform, a guard)
  • What do you know about Sentinel like products? (hystrix - next generation microservice products)
  • How does sentinel limit the flow of requests? (interceptor provided based on sentinel dependency)
  • What current limiting algorithms do you know? (counter, token bucket, funnel algorithm, sliding window algorithm,...)
  • What is Sentinel's default current limiting algorithm? (sliding window algorithm)

Sentinel flow control rule analysis

Threshold type

  • QPS(Queries Per Second): when the resource corresponding to the relevant url is called, the QPS will limit the flow when it reaches the stand-alone threshold.
  • Number of threads: when calling the resources corresponding to the relevant url, the flow will be limited when the number of threads reaches the stand-alone threshold.

Set current limiting mode

Sentinel's flow control mode represents the flow control mode. It defaults to [direct], as well as association and link.

Direct mode:

Sentinel's default flow control processing is direct - > quick failure.

 

Association mode:

When the associated resource reaches the specified threshold, it limits itself. For example, when the associated resource is set to ur2, if the qps threshold of the associated resource url2 exceeds 1, Current limiting url1 interface (does it feel overbearing that the associated resources have reached the threshold and the resource interface has been restricted). What are the application scenarios of this association mode? For example, there are two important interfaces in the order service, one is to read the order information and the other is to write the order information. In the high concurrency business scenario, both interfaces will occupy resources. If you read the order information If the interface access is too large, the performance of the write interface will be affected. In business, if we want to write orders, we should give priority to the write order interface. Then you can use the association pattern; Set the write interface on the associated resource, and set the read interface for the resource name; This gives priority to writing. Once there are many write requests, the read requests are limited. for example

Step 1: add a method in ProviderSentinelController, for example:

 @GetMapping("/sentinel02")
   public String doSentinel02(){
     return "sentinel 02 test  ...";
   }


Step 2: make current limiting design in sentinel, for example


Step 3: open two test windows, access / provider/sentinel02, and check the status of / provider/sentinel01, for example:

Link mode

The link mode only records the traffic at the specified link entrance. That is, when multiple services call the specified resource, if the traffic exceeds the specified threshold, the flow will be limited. The called method is annotated with @ SentinelResource, and then called with different service methods. If service A sets the current limit of link mode, it will not be affected in service B. Now practice the link mode, for example:

For example, now design a business object. The code is as follows (for simplicity, it can be written directly inside the startup class):

Step 1: create a ResourceService class in the specified package. The code is as follows:

package com.jt.provider.service;
@Service
public class ResourceService{
    @SentinelResource("doGetResource")
    public String doGetResource(){
        return "doGetResource";
    }
}


Step 2: add a method in ProviderSentinelController, for example:

@Autowired
    private ResourceService resourceService;
    @GetMapping("/sentinel03")
    public String doSentinel03() throws InterruptedException {
        resourceService.doGetResource();
        return "sentinel 03 test";
    }


Step 3: configure current limiting rules in sentinel, for example:

 

After setting the link flow control rules, frequently access the current limiting link to detect whether 500 exceptions will occur, such as

Note: if the flow control mode is link mode, it is sentinel 1.7 2 and later versions, Sentinel Web filter will aggregate all URL entries as sentinel by default_ spring_ web_ Context. Therefore, the current limit for the specified link alone will not take effect. It needs to be in application YML add the following statement to turn off URL PATH aggregation, for example:

sentinel:
     web-context-unify: false


After this configuration is set, start the service to limit the current of the specified specific link.

In addition, we can also handle the exceptions after current restriction based on the method described in the @ SentinelResource annotation. The steps are as follows:

Step 1: define blockHandlerClass, for example:

package com.jt.provider.service;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class ResourceBlockHandler {
    /**
     * Note that the exception type in this method must be BlockException(
     * It is the parent type of all current limiting, degradation and other exceptions, and the return of the method
     * The value type is the return value type described by the @ SentinelResource annotation,
     * Other parameters of the method are the method parameters described by the @ SentinelResource annotation,
     * And this method must be static
     * @param ex
     * @return
     */
    public static String call(BlockException ex){
        log.error("block exception {}", ex.getMessage());
        return "Visits are too frequent,Wait a moment and visit again";
    }
}


Step 2: modify the attribute definition in the @ SentinelResource annotation, for example:

@SentinelResource(value="doGetResource",
        blockHandlerClass = ResourceBlockHandler.class,
        blockHandler = "call")
public String doGetResource(){
    return "do get resource";
}


The third step: in the controller method, we call the @Sentinel annotation method, for example:

/**
 * Demonstrate link current limiting
 * @return
 */
@GetMapping("/sentinel03")
public String doSentinel03(){
   return resourceService.doGetResource();
   //return "sentinel 03 test";
}

Section interview analysis

  • Do you know the threshold application types in sentinel? (two types - QPS, number of threads)
  • What are the default current limiting modes in Sentinel's current limiting rules? (direct connection, association, link)
  • What are the current limiting effects of Sentinel? (fast failure, warm-up, queuing)

Sentinel downgrade application practice

summary

In addition to flow control, fusing and degrading unstable resources in the call link is also one of the important measures to ensure high availability. Due to the complexity of the call relationship, if a resource in the call link is unstable, it will eventually lead to the accumulation of requests.
Sentinel fusing degradation will limit the call of a resource in the call link when it is in an unstable state (such as call timeout or abnormal proportion increase), so as to make the request fail quickly and avoid affecting other resources and causing cascading errors. After the resource is degraded, the call to the resource will automatically fuse within the next degradation time window (the default behavior is to throw DegradeException).

preparation

Add the doSentinel05 method in the ProviderController class. Based on this method, demonstrate the current limit in the slow call process. The code is as follows:

     //AtomicLong class supports thread safe self increment and self decrement operations
    private AtomicLong atomicLong=new AtomicLong(1);
    @GetMapping("/sentinel05")
    public  String doSentinel05() throws InterruptedException {
        //Get the value of the self incrementing object, and then add 1
        long num=atomicLong.getAndIncrement();
        if(num%2==0){//Simulate 50% slow call ratio
           Thread.sleep(200);
        }
        return "sentinel 04 test";
    }

Note: we set sleep in this method to demonstrate slow call (long response time)

Sentinel demotion getting started

Next, we perform service degradation and application practice based on a request link, for example:

Step 1: after the service is started, select the link to be degraded, as shown in the figure:

Step 2: select the link to be degraded, as shown in the figure:

 

This indicates that "slow call proportion" is selected for the fusing strategy, which means that when the number of requests exceeds 3, if 30% of the average response time exceeds 200 milliseconds, the request will be fusing for 20 seconds, and it will return to normal after 10 seconds.

Step 3: refresh the specified link, visit the test multiple times, and check whether current limit will appear on the page (the default exception is DegradeException)

We can also debug breakpoints, add breakpoints inside the handle method in DefaultBlockExceptionHandler, and analyze the exception type. If the exception type is DegradeException, it will be degraded.

Sentinel exception handling

The system provides a default exception handling mechanism. If the default handling mechanism does not meet our needs, we can define it ourselves. In terms of definition, you can directly or indirectly implement the BlockExceptionHandler interface and hand over the object to spring for management.

package com.jt.provider.controller;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Custom current limiting, degradation and other exception handling objects
 */
@Slf4j
@Component
public class ServiceBlockExceptionHandler
     implements BlockExceptionHandler {
    /**
     * Used to handle BlockException type and subclass type exceptions
     */
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       BlockException e) throws Exception {
        //Set response data encoding
        response.setCharacterEncoding("utf-8");
        //Tell the client the type of response data and the encoding of the client display content
        response.setContentType("text/html;charset=utf-8");
        //Respond to the client with a string in json format
        //String str="{\"status\":429,\"message \ ": \" too frequently accessed \ "}";
        Map<String,Object> map=new HashMap<>();
        map.put("status", 429);
        map.put("message","Visits are too frequent");
        String jsonStr=new ObjectMapper().writeValueAsString(map);
        PrintWriter out = response.getWriter();
        out.print(jsonStr);
        out.flush();
        out.close();
    }
}

 

Section interview analysis

  • What is degraded fusing? (stop external applications from accessing the service, trip in life, roadblock setting - this road is blocked)
  • Why fuse? (the average response speed becomes slower and slower or exceptions often occur, which may lead to call chain accumulation and eventually system crash)
  • Who is the parent class of the degraded exception in Sentinel current limiting? (BlockException)
  • Who is the exception thrown by the bottom layer of the system when Sentinel is degraded? (DegradeException)
  • Who is the exception handling interface in Sentinel? (BlockExceptionHandler)
  • The default implementation class under the exception handling interface in Sentinel is? (DefaultBlockExceptionHandler)
  • What if the default exception handling rules in Sentinel do not meet our needs? (self defined)
  • How do we define exception handling in Sentinel? (directly or indirectly implement BlockExceptionHandler)
  • What are Sentinel downgrade strategies? (slow call ratio, exception ratio, different constant)

Sentinel hotspot rule analysis (key)

summary

What are hot spots? Hot spots are frequently accessed data. For example:

  • Commodity ID is a parameter that counts and limits the most frequently purchased commodity ID in a period of time.
  • User ID is a parameter, which limits the user ID frequently accessed over a period of time.

Hotspot parameter current limiting will count the hotspot data in the incoming parameters, and limit the current of 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 is only effective for resource calls containing hotspot parameters. Sentinel will use the LRU policy to count the most frequently accessed hotspot parameters recently, and combine the token bucket algorithm for parameter level flow control.

quick get start

Step 1: add the following methods in SCA provider, for example:

    @GetMapping("/sentinel/findById")
        @SentinelResource("resource")
        public String doFindById(@RequestParam("id") Integer id){
            return "resource id is "+id;
        }


Step 2: after the service is started, select the hotspot link to limit the current, as shown in the figure:

Step 3: set the hot spot to limit current, as shown in the figure:

 

The current limiting mode of the hotspot rule is only QPS mode (this is called hotspot). The parameter index is the subscript of the method parameter annotated by @ SentinelResource. 0 represents the first parameter and 1 represents the second parameter. The stand-alone threshold and the statistical window duration indicate that the current is limited when the time in this window exceeds the threshold.

Step 4: access the hotspot parameter method many times, and the following interface will appear on the front end, as shown in the figure:

Then, the following exceptions appear in the background, indicating that the current limiting is successful.

com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException: 2


In fact, the hotspot parameter is a special flow control, and the flow control setting is for the whole request; However, the hotspot parameter can be set to a specific parameter or even the value of the parameter, so that flow control management can be more flexible.
It is generally used in the special treatment of some special resources, such as the flow of some commodities is large and the flow of other commodities is normal, so the scheme of flow restriction with hot spot parameters can be used.

Specific parameter design

Configuration parameter exceptions, as shown in the figure:

Here, it means that the threshold is 100 when the parameter value is 5, and the threshold of other parameter values is 1

 

Section interview analysis

  • How to understand hot data? (frequently accessed data, some commodities, articles, a video)
  • What are the current limiting rules for hot data? (mainly for current limiting design based on parameters)
  • How to understand the special parameters in hot data? (threshold design of a parameter value in hot spot current limiting)
  • What are the underlying exceptions after the access of hot data is limited? (ParamFlowException)

Sentinel system rules (understand)

summary

During the operation of the system in the production environment, we often need to monitor the status of the server and see the utilization rate of server CPU, memory, IO, etc; The main purpose is to ensure the normal operation of the server and not be crashed by some applications; Moreover, the maximum throughput of the system is maintained on the premise of ensuring stability.

quick get start
Sentinel's system protection rule is to control the application level inlet flow, and monitor the application data from the five dimensions of overall Load, RT, inlet QPS, number of threads and CPU utilization of a single machine, so as to make the system run at the maximum throughput and ensure the overall stability of the system. As shown in the figure:


System rule is a global design rule, in which,

  • Load (only valid for Linux / Unix like machines): system protection is triggered when system load1 exceeds the threshold and the current number of concurrent threads exceeds the system capacity. The system capacity is calculated by the system's maxQps * minRt. The setting reference value is generally CPU cores * 2.5.
  • CPU utilization: system protection is triggered when the system CPU utilization exceeds the threshold (value range: 0.0-1.0).
  • RT: when the average RT of all inlet flows on a single machine reaches the threshold, the system protection is triggered, and the unit is milliseconds.
  • Number of threads: system protection is triggered when the number of concurrent threads of all inlet traffic on a single machine reaches the threshold.
  • Inlet QPS: when the QPS of all inlet flows on a single machine reaches the threshold, the system protection is triggered.

Note: the system protection rules apply the overall dimension, not the resource dimension, and are only effective for inlet traffic. Entry traffic refers to the traffic entering the application (EntryType.IN), such as Web services.

Section interview analysis

  • How to understand the system rules in sentinel? (it is a control rule for all links and a system protection strategy)
  • What are Sentinel's common system rules? (RT,QPS,CPU, thread, load Linux, Unix)
  • What exceptions will be thrown by the underlying layer after the Sentinel system protection rule is triggered? (SystemBlockException)

Sentinel authorization rules (important)

summary

In many cases, we need to restrict whether resources can pass according to the caller. At this time, we can use Sentinel's black-and-white list control function. The black-and-white list restricts whether the resource passes according to the request origin of the resource. If the white list is configured, it can only pass if the request source is in the white list; if the blacklist is configured, it will not pass if the request source is in the blacklist, and the rest of the requests pass. For example, the blacklist in wechat.

quick get start

sentinel can design authorization rules based on black-and-white list, as shown in the figure:

The authorization rule is very simple. It mainly has the following configuration items:

  • Resource Name: the object of the flow restriction rule
  • Flow control application: the rule value set in the corresponding blacklist / whitelist. Multiple values are separated by commas
  • Authorization type: white list, blacklist (no access allowed)

Case realization:

Define a request parser, which is used to parse the request and return the parsing result. After the sentinel bottom layer intercepts the user's request, it will parse the request data based on this object to determine whether it complies with the black-and-white list rules, for example:

Step 1: define the implementation class of the RequestOriginParser interface, parse the request parameter data in the interface method and return it. The bottom layer will apply the authorization rules based on this return value.

@Component
public class DefaultRequestOriginParser implements RequestOriginParser {
    @Override
    public String parseOrigin(HttpServletRequest request) {
        String origin = request.getParameter("origin");//The parameter name here will be consistent with the parameter name in the request
        return origin;
    }
}

Step 2: define flow control rules, as shown in the figure:

Step 3: execute resource access and detect the application of authorization rules. When the configured flow control application value is app1, if the rule is blacklist, it will be based on
http://ip:port/path?origin=app1 The request cannot be passed. The request processing flow is shown in the figure below:

 

Expansion: try to design black-and-white list rules based on request ip, for example:

Step 1: modify the request parser, obtain the request ip and return it, for example:

@Component
public class DefaultRequestOriginParser  implements RequestOriginParser {
    //Parse request source data
    @Override
    public String parseOrigin(HttpServletRequest request) {
        //Obtain the ip address in the access request and design the black-and-white list based on the ip address (for example, write the ip address in the flow control application column)
        String ip= request.getRemoteAddr();
        System.out.println("ip="+ip);
        return ip;
    }//The value of the black-and-white list in the authorization rule, which comes from the return value of this method
}


Step 2: define authorization rules on sentinel console, for example:

Step 3: after the rule is defined, conduct access test based on your ip address to detect the effect of black and white list

Section interview analysis

1. How to understand the authorization rules in Sentinel? (a simple authorization policy for access to specified resources)
2. How are Sentinel's authorization rules designed? (white list and blacklist)
3. How to understand the white list in Sentinel? (list of resources allowed to access)
4. How to understand the blacklist in Sentinel? (list of resources not allowed to access)
5. How does sentinel identify white list and blacklist? (specific rules are detected in the interceptor by calling the method of the RequestOriginParser object)
6. What is the function of RequestOriginParser class in authorization rules? (analyze the flow control application value and check whether the value passed in during service access is the same as the return value of the parseOrigin method of RequestOriginParser.)

Summary

In short, Sentinel can provide flow restrictions at the API interface level for high concurrent applications such as second kill, rush purchase, ticket grabbing and ticket canvassing, so that the access of users with sudden surge of traffic is subject to unified control, and reasonable traffic release rules are used to enable users to get services normally.

Analysis of key and difficult points

The background of Sentinel's birth? (whether the number of computers is limited, the processing capacity is limited, the concurrency is large or the burst traffic is large)
Integration and initialization of sentinel environment in service? (add dependency - two, sentinel configuration)
Sentinel's current limiting rules? (threshold type - QPS & number of threads, current limiting mode - direct, association, link)
Sentinel's downgrading (fusing) strategy? (slow call, exception ratio, different constant)
Sentinel's hot rule design (mastery)?
Sentinel system rule design? (understand that the global rule definition is valid for all requests)
Sentinel authorization rule design? (Master, black and white list)

FAQ analysis

  • Why limit current?
  • What current limiting frameworks do you know? (sentinel)
  • What are the commonly used current limiting algorithms? (counting, token bucket - movie ticket, leaky bucket - funnel, sliding window)
  • What current limiting rules does Sentinel have? (QPS, number of threads)
  • What current limiting modes does Sentinel have? (direct, Association - create and query orders, link current limit - no number limit outside the Sixth Ring Road in Beijing, but no number limit on the Fifth Ring Road)
  • What are Sentinel's downgrading (fusing) strategies? (slow call - response time, exception proportion - exception proportion, different constant)
  • Hotspot data in Sentinel's hotspot rules? (hot goods, microblog celebrities, new movies)
  • How to understand the black and white list in Sentinel authorization rules?

Bug analysis

  • Dependency download failed (maven local library, network, image warehouse)
  • Word error (spelling error)

Core knowledge points

  • Background of service flow restriction and degradation (service governance)
  • Sentinel current limiting introduction practice (console 8180 definition rules, client service application rules: dependency, configuration)
  • Sentinel common current limiting modes (direct, associated - > guaranteed core services, link - > traffic lights)
  • @SentinelResource annotation function and current limiting exception handling
  • Custom exception flow limiting processing class (SentinelBlockExceptionHandler)

 

Analysis of common problems

  • Why current limiting and degradation? (the processing capacity of the system is limited, and the reliable operation of the system can be ensured by current limiting)
  • What algorithms do you know about sentinel current limiting? (counter, token bucket, leaky bucket, sliding window algorithm ~ sentinel default)
  • Sentinel common current limiting mode? (direct, Association - > guarantee core business, link - > traffic light)
  • @What attributes have you used for SentinelResource annotation? (describe resource nodes in link current limiting)
  • What are the common current limiting effects of Sentinel? (fast failure, warm-up, queuing)
  • What is the exception type when current limit is triggered in Sentinel? (all subclasses of BlockException type)
  • How to process the current limiting results? (there is a default processing scheme, and we can also define our own processing rules - implement the BlockExceptionHandler interface)
  • Basic principle of Sentinel current limiting? (the bottom layer intercepts service requests, and then restricts resource access through flow control rules)

 

Common Bug analysis

  • sentinel service can't start? (to configure JDK environment variable path, use JDK8 version)
  • Does the sentinel panel not display our services? (dependency, configuration > be sure to pay attention to indentation, access first, zoom in - clear idea cache restart)
  • After configuring sentinel, the business service cannot be started? (most of them are configured incorrectly)

Exercise 1 (customized handling of sentinel current limit exception based on business)

Custom processing of sentinel current limiting exceptions based on business, for example:

package com.jt.provider.controller;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**Sentinel In, the default current limiting exception handling interface type is BlockExceptionHandler, if we want to define it ourselves
 For exception handling rules, you can define classes to implement this interface, and then handle exceptions.*/
@Component
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request,HttpServletResponse response, BlockException e) throws Exception {
        //Set response data encoding
        response.setCharacterEncoding("utf-8");
        //Tell the browser what type of content to respond to and how to encode it
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(429);
        PrintWriter out = response.getWriter();
        out.print("<h1>The request is throttled</h1>");
        out.flush();
        out.close();
    }
}

 

Exercise 2

  • Understand common current limiting algorithms
  • Complete Sentinel service degradation, hotspot rule design, system rule setting and authorization rule setting (required)
  • The spring mvc interceptor is used to restrict the time access of the specified resources in the system?

Step 1: interceptor principle analysis (review interceptors in spring mvc), for example:

Step 2: customize the interceptor, for example:

package com.jt.provider.interceptor;
public class TimeInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 
    throws Exception {
        System.out.println("==preHandle==");
        //1. Get the current time
        LocalTime now = LocalTime.now();//LocalTime is an api in jdk8 to get the current time
        //2. Obtain the current hour and make logical judgment
        int hour = now.getHour();//8:10~8
        System.out.println("hour="+hour);
        if(hour<9||hour>18){
            throw new RuntimeException("Please at 9~18 Time range access");//return false
        }
        return true;//false this is the end of the request. true means release. Subsequent interceptors or controller objects will be executed
    }
}


Step 3: configure the interceptor, for example:

package com.jt;
@Configuration
public class SpringWebConfig implements WebMvcConfigurer {
    /**
     * Register the interceptor (add it to the spring container) and specify the interception rules
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TimeInterceptor())
                .addPathPatterns("/provider/sentinel01");
    }
}


Step 4: open the browser, access the / provider/sentinel01 path, and access the access results.

Keywords: Java Back-end

Added by nhan on Wed, 29 Dec 2021 16:02:32 +0200