当前位置:网站首页>Basic application of sentinel series

Basic application of sentinel series

2022-06-13 05:40:00 codain

Achieve current limiting ,Sentinel It is mainly implemented with the core library , There are mainly the following steps :

1、 Define resources

2、 Define current limiting rules

3、 Check if the rules are in effect

among , Resources are the basic elements that need to be protected by current limiting


1、Sentinel Achieve current limiting

① introduce Sentinel Core library dependency

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-core</artifactId>
    <version>1.7.1</version>
</dependency>

② Create a simple and common business method , as follows

//  Method to be limited 
private static void doSth() {
    try (Entry entry = SphU.entry("doSth")) {
        // Business processing 
        System.out.println("doSth..." + System.currentTimeMillis());
    } catch (BlockException e) {
        // Deal with the logic that is throttled 
        //System.out.println(" It's restricted ...");
    }
}

③ Create current limiting rules

private static void initFlowRules() {
    List<FlowRule> rules=new ArrayList<>();
    FlowRule rule=new FlowRule();
    // Resources that need to be protected , The name should be the same as the method above SphU.entry The input parameters of are consistent 
    rule.setResource("doSth");
    // Current limiting threshold 
    rule.setCount(20);
    // Current limiting threshold type ,QPS Pattern 1 Or concurrent thread count mode 0
    rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    rules.add(rule);
    FlowRuleManager.loadRules(rules);
}

④ To write main Method , Perform log viewing and analysis

public static void main(String[] args) {
    initFlowRules();
    while (true) {
        doSth();
    }
}

⑤ Log text analysis :

INFO: log output type is: file
INFO: log charset is: utf-8
INFO: log base dir is: C:\Users\caobing\logs\csp\
INFO: log name use pid is: false

Let's check this dir The name of the project under +metrics.log. Date log file

1645596272000|2022-02-23 14:04:32|doSth|20|333|20|0|0|0|0|0
1645596273000|2022-02-23 14:04:33|doSth|20|18941|20|0|0|0|0|0
1645596274000|2022-02-23 14:04:34|doSth|20|77021|20|0|0|0|0|0
1645596275000|2022-02-23 14:04:35|doSth|20|117691|20|0|0|0|0|0
1645596276000|2022-02-23 14:04:36|doSth|20|163572|20|0|0|0|0|0

Explain what each paragraph means  

 Time stamp         | date                | resources    | Number of requests passed  | Number of blocked requests   | Number of requests successfully executed  | Number of abnormal        | Average response time  | Number of priority requests  | Concurrency       | The resource type 
timestamp    |yyyy-MM-dd HH:mm:ss|resouce|passQps     |blockQps      |successQps      |exceptionQps|rt          |occupiedPassQps |concurrency|classification
1645596276000|2022-02-23 14:04:36|doSth  |20          |163572        |20              |0           |0           |0               |0          |0

From the log above , This program executes steadily every second and outputs 20 Time , It is the same as the predetermined rule threshold , The number of rejected requests per second is as high as 16 More than ten thousand times , As low as 300 many times

2、 How resources are defined

1、 Through the top try..catch... We define a resource by throwing exceptions , When this resource is throttled , Will throw an exception , The code is as follows :

    //  Method to be limited 
    private static void doSth() {
        try (Entry entry = SphU.entry("resourceName")) {
            // Business processing 
        } catch (BlockException e) {
            // Deal with the logic that is throttled 
        }
    }

Among them the resourceName It can be a method name 、 Interface name or other unique identifier

2、 You can also use Boolean values as conditions to define resources , The code is as follows

//  Method to be limited 
private static void doSth() {
    if(SphU.entry("resourceName")) {
        try{
            // Business processing 
        } finally{
            sph0.exit();
        }
    }else{
        // Resource access flow restriction 
    }
}

You need to call... After the resource is used up Sph0.exit(), Otherwise, an error call chain exception will be reported , Throw out ErrorEntryFreeException It's abnormal

3、 Use @SentinelResource To define resources

@SentinelResource(value="resourceName",blockHandler="userBlockHander")
public User getUserById(int id){
    // Code ellipsis 
}

// Define the bottom logic 
public User userBlockHander(int id,BlockException e){
    // Method after current limiting 
}

Be careful : Parameters in comments blockHandler It will be called after the current limit starts , And the distribution corresponding to this parameter value must be the same as the original getUserById The return value of 、 Consistent parameters , Once again, add a BlockException Parameters

3、Sentinel Resource protection rules

Sentinel Support many protection rules , such as : Flow control rules 、 Fusing degradation rules 、 System protection rules 、 Hot spot parameter rules 、 Source access control rules

The complete current limiting rule setting code is as follows :

private static void initFlowRules() {
        List<FlowRule> rules=new ArrayList<>();
        FlowRule rule=new FlowRule();
        // Resources that need to be protected , The name should be the same as the method above SphU.entry The input parameters of are consistent 
        rule.setResource("doSth");
        // Current limiting threshold 
        rule.setCount(20);
        // Current limiting threshold type ,QPS Pattern 1 Or concurrent thread count mode 0
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Whether the call source needs to be limited , Default default, I don't know the source 
        rule.setLimitApp("default");
        // Call relationship current limiting policy -- direct 、 link 、 relation 
        rule.setStrategy(RuleConstant.STRATEGY_CHAIN);
        // Flow control behavior , Such as direct rejection 、 Waiting in line 、 Slow start mode . The default is to reject directly 
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
        // Is it cluster current limiting , The default is false
        rule.setClusterMode(false);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
}

3.1、 Concurrency and QPS Flow control of

Sentinel There are two types of flow control Statistics , It's all through grade Property :

  • Number of concurrent threads (FLOW_GRADE_THREAD)
effect Used to protect business threads from exhaustion
give an example A The service call B service , however B The service is unstable or delayed due to network or other reasons , Then it will affect A Normal service , As a result, the throughput will drop and occupy a lot of threads , It is more likely to cause the thread pool to run out
solve Sentinel Is to count the number of context threads currently requested , If the expected threshold is exceeded , Will refuse new requests
  • QPS(FLOW_GRADE_QPS)
effect When QPS When the threshold is exceeded , Flow control will be triggered
usage

adopt contolBehavior To set , The specific values are as follows

① Direct refused to (RuleConstant.CONTROL_BEHAVIOR_DEFAULT)

Default mode , That is, when the number of requests exceeds the threshold , I'll throw one FlowException abnormal

② Cold start , Also known as preheating 、Warm UP(RuleConstant.CONTROL_BEHAVIOR_WARM_UP)

In a nutshell : The maximum number of concurrency that can be handled is 400, But suddenly it happened , Tens of thousands , So at this point ,Sentinel It will gradually raise the concurrency threshold for processing within a certain period of time , This process is preheating , Instead of concurrent explosion , This value will be directly pulled to the maximum in one fell swoop

③ Line up at a constant speed (RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)

Simply put, it means fixing a threshold : How many seconds per request

④ Cold start + Line up at a constant speed (RuleConstant.CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER) 

combination ②③ advantage , Make processing concurrency more elegant

3.2、 Call the relational traffic policy

Calling relationship includes caller and caller , One method may call another method , Other methods can call other methods , This will form a call chain , In fact, it triggers flow control according to different call dimensions

  • Current limiting according to the caller
Concept Flow control according to the request source
usage

Set up limitApp Attribute is enough

①default: The identity does not distinguish the calling source , Anyone who comes in will conduct current limiting statistics , When the threshold value is reached, the current will be limited

②${something}: Set specific callers , It can be a method name

③other: The logo is for ${something} Control by other callers

  • Limit the current according to the call link entry
In a nutshell , Restrict for entry , such as A service , There are... Upstream B and C Respectively called A, Then we can only aim at B The portal performs request statistics , It is similar to the above caller restriction
  • Resource flow control with relationship
In a nutshell :A and B Services may call each other or both C, Explain this AB There is a certain correlation between the two services , Or brother , Call each other , Or the enemy , Fight for resources , Then there will be if A Frequent requests , May affect B Efficiency of execution , Therefore, you can restrict one of the resources through associated flow control

4、Sentinel Realize service fusing

Sentinel And current limiting , Code similarity , Only current limiting uses FlowRule, The fuse uses DegradeRule, That's the difference between the two , The code is as follows

private static void initDegradeRule(){
    List<DegradeRule> rules=new ArrayList<>();
    DegradeRule rule = new DegradeRule();
    // Resources that need fusing 
    rule.setResource("resourceName");
    rule.setCount(20);
    // Fusing strategy , Support second level RT、 Abnormal proportion 、 Number of minute level exceptions , The default is RT
    /**
    * RuleConstant.DEGRADE_GRADE_RT: If the number of requests per second is stable at 5 individual , Corresponding average response 
    *  The time has exceeded the threshold ms, Then the call to this method will be automatically blown in the next second , The system will throw 
    * DegradeException abnormal 
    *
    * RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO: If the number of requests per second is greater than or equal to 5
    * ( The default value is ), And the ratio of the total number of exceptions per second to the total throughput exceeds the threshold count Returns a 
    * [0.0,1.0], Express 0-100%, At this time, resources will be degraded , Again , In the next time , For this 
    *  Method will trigger fusing 
    *
    * RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT: When a resource is abnormal in the last minute 
    *  After the amount exceeds the threshold , It will trigger a fuse , Here is a point to remember , Is that if timeWindows Less than one 
    *  minute , That is to say 60s, It is still possible to enter the fusing state after the fusing state is ended 
    */
    rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
    // The time window for fusing and degrading , The unit is seconds , It means how long it will automatically fuse after triggering fuse degradation 
    rule.setTimeWindow(10);
    // The minimum number of requests that trigger abnormal fusing , When the number of requests is less than the set value, even if the abnormal proportion exceeds the threshold ,
    // Will not set off , The default is 5
    rule.setMinRequestAmount(5);
    // Mean in RT In mode ,1s The average number of requests that last in the RT The fuse is triggered when the threshold is exceeded , The default is 5
    rule.setRtSlowRequestAmount(5);
    rules.add(rule);
}
原网站

版权声明
本文为[codain]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280508406840.html