SpringCloud(13) Sentinel 1.8.2 console use

I. Introduction

Official website document https://sentinelguard.io/zh-cn/index.html

Two, Sentinel installation

tips: docker-composeInstall by way

# 环境准备
git clone https://gitee.com/zhengqingya/docker-compose.git
cd docker-compose/Liunx

# 运行
docker-compose -f docker-compose-sentinel.yml -p sentinel up -d

insert image description here

3. Instructions for use of Sentinel

insert image description here

1. Real-time monitoring

Display in seconds

insert image description here

2. Cluster link

Only display the resources called after the service starts

insert image description here

3. Flow control rules

insert image description here

QPS: query rate per second, the number of requests that a server can respond to per second
Number of concurrent threads: number of concurrent threads accessing the resource

flow control mode
  1. Direct: direct operation, limit current resources
    insert image description here

  2. Association: When the associated resource reaches the threshold, limit the flow of itself (ex: set the associated resource B, when B reaches the threshold, limit the flow of A)
    insert image description here

  3. Link: only counts the requests that enter the current resource from the specified resource. It is a flow limit for the request source
    A -> common
    B -> common
    is only limited to the common accessed through the entrance B, and A's free access will not be affected
    (tips: if B If common can be requested normally every time, the effect is the same as direct flow control, if common is not requested normally, it is equivalent to unlimited flow processing)
    insert image description here

Tips: link test needs to be configured, spring.cloud.sentinel.web-context-unify: falseclose call link convergence => implement link flow control

Flow control effect
  1. Fail fast: Once the threshold is reached, new requests are immediately rejected
  2. Warm Up: Preheat/cold start mode, let the passing flow increase slowly, gradually increase to the upper threshold within a certain period of time, give the cold system a warm-up time, and avoid the cold system from being overwhelmed
  3. Queuing and waiting: In the face of sudden traffic, queuing passes through at a uniform speed, such as message queues, which correspond to the leaky bucket algorithm. Selecting queuing can only use QPS (not the number of concurrent threads), and it will fail when the timeout is reached
    insert image description here

4. Fuse rules

slow call ratio

When the number of requests exceeds 3 and the maximum RT (response time) exceeds 10 milliseconds within the unit statistics time, 10% will fuse the request. The duration of the fuse is 3 seconds. After 3 seconds, the response time of a request < RT will end the fuse Back to normal
insert image description here


The exception downgrade is only for business exceptions, and it does not take effect on the exception (BlockException) of Sentinel current limiting downgrade itself. In order to count the abnormal ratio or the number of abnormalities, it is necessary Tracer.trace(ex)to record business exceptions through .
insert image description here

abnormal ratio

When the number of requests exceeds 3 and the proportion of abnormalities is greater than the threshold 10% within the unit statistics time, the fuse will be automatically cut off. If the next request is successfully completed (without errors), the fuse will end, otherwise it will be blown again.
insert image description here

Abnormal number

When the number of requests exceeds 3 and the number of exceptions is greater than 10% of the threshold within the unit statistics time, the fuse will be automatically broken. If the next request is successfully completed (without errors), the fuse will end, otherwise it will be blown again.
insert image description here

5. Hotspot rules

a. Add annotations to the method@SentinelResource("xxx")

b. The console is newly added热点规则

Only valid for resource calls containing hotspot parameters

Parameter index: 0 for the first parameter, 1 for the second parameter.
It takes effect when the unit statistics window is within 1s and the number of requests exceeds the stand-alone threshold 1
insert image description here

6. System rules

Sentinel system self-adaptive current limiting controls application ingress traffic from the overall dimension, combined with monitoring indicators in several dimensions such as application Load, CPU usage, overall average RT, ingress QPS and number of concurrent threads, through adaptive flow control strategy , so that the system's ingress traffic and system load can reach a balance, so that the system can run at the maximum throughput as much as possible while ensuring the overall stability of the system.

  • Load self-adaptation (only valid for Linux/Unix-like machines): the system's load1 is used as a heuristic indicator for self-adaptive system protection. When the system load1 exceeds the set heuristic value, and the current number of concurrent threads of the system exceeds the estimated system capacity, the system protection (BBR phase) will be triggered. System capacity is derived from system maxQps * minRtestimates. The setting reference value is generally CPU cores * 2.5.
  • CPU usage (version 1.5.0+): When the system CPU usage exceeds the threshold, system protection will be triggered (value range 0.0-1.0), which is more sensitive.
  • Average RT : When the average RT of all ingress traffic on a single machine reaches the threshold, system protection is triggered, and the unit is milliseconds.
  • Number of concurrent threads : When the number of concurrent threads of all ingress traffic on a single machine reaches the threshold, system protection is triggered.
  • Ingress QPS : When the QPS of all ingress traffic on a single machine reaches the threshold, system protection is triggered.

insert image description here

7. Authorization rules

a. The implementation RequestOriginParserclass obtains the flow control application value

@Component
public class SentinelRequestOriginParser implements RequestOriginParser {
    
    

    @Override
    public String parseOrigin(HttpServletRequest request) {
    
    
        // 这里怎么去取值可自定义
        String origin = request.getParameter("origin");
        if (StringUtils.isBlank(origin)) {
    
    
            origin = " ";
        }
        return origin;
    }

}

b. New authorization rules in the console

Services in the whitelist can be accessed normally, while services in the blacklist are denied access
insert image description here

8. Cluster flow control

Deployment method:

  1. 独立模式: Token Server runs alone
    insert image description here

  2. 嵌入模式: Token Server and service are started in the same process, no need to deploy separately
    insert image description here

  • Token Client: The cluster flow control client is used to request tokens from the Token Server to which it belongs. The cluster current limiting server will return the result to the client to decide whether to limit the current. The communication bottom layer of Sentinel cluster flow control is realized by Netty.
  • Token Server: The cluster flow control server handles the request from the Token Client, and judges whether the token should be issued (whether it is allowed to pass) according to the configured cluster rules.

Let's study the cluster flow control later when we have time^_^

9. Machine list

Client Instance Monitoring

If the health status is 失联, you need to selectively remove it yourself
insert image description here

insert image description here

Fourth, sentinel unified exception handling

@Component
public class MySentinelExceptionHandler implements BlockExceptionHandler {
    
    

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws Exception {
    
    
        String msg = null;
        if (ex instanceof FlowException) {
    
    
            msg = "访问频繁,请稍候再试";
        } else if (ex instanceof DegradeException) {
    
    
            msg = "系统降级";
        } else if (ex instanceof ParamFlowException) {
    
    
            msg = "热点参数限流";
        } else if (ex instanceof SystemBlockException) {
    
    
            msg = "系统规则限流或降级";
        } else if (ex instanceof AuthorityException) {
    
    
            msg = "授权规则不通过";
        } else {
    
    
            msg = "未知限流降级";
        }

        // http状态码
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(ApiResult.fail(msg)));
    }

}

5. This article tests the api code

You can view https://gitee.com/zhengqingya/small-tools

@Slf4j
@RestController
@RequestMapping("/sentinel")
@Api(tags = "sentinel")
public class SentinelController extends BaseController {
    
    

    @Resource
    private ISentinelService iSentinelService;

    @Resource
    private IDemoClient iDemoClient;

    private Long num = 0L;

    private Long requestCommon() {
    
    
        return this.iDemoClient.flowCommon();
    }

    /**
     * http://127.0.0.1:20040/sentinel/flow/A
     */
    @SneakyThrows(Exception.class)
    @GetMapping("flow/A")
    @ApiOperation("A")
    public Long flowA() {
    
    
        this.num++;
        if (this.num > 6) {
    
    
            return this.num;
        }
        // 只有正常请求common,才能启动链路限流规则
        this.requestCommon();
        return RandomUtil.randomLong();
    }

    /**
     * http://127.0.0.1:20040/sentinel/flow/B
     */
    @SneakyThrows(Exception.class)
    @GetMapping("flow/B")
    @ApiOperation("B")
    public Long flowB() {
    
    
        this.requestCommon();
        return RandomUtil.randomLong();
    }

    /**
     * http://127.0.0.1:20040/sentinel/flow/C
     */
    @SneakyThrows(Exception.class)
    @GetMapping("flow/C")
    @ApiOperation("C")
    public Long flowC() {
    
    
        TimeUnit.MILLISECONDS.sleep(200);
        return RandomUtil.randomLong();
    }

    /**
     * http://127.0.0.1:20040/sentinel/flow/D
     */
    @SneakyThrows(Exception.class)
    @GetMapping("flow/D")
    @ApiOperation("D")
    public Long flowD() {
    
    
        try {
    
    
            int a = 1 / 0;
        } catch (Exception e) {
    
    
            if (!BlockException.isBlockException(e)) {
    
    
                Tracer.trace(e);
            }
            throw e;
        }
        return RandomUtil.randomLong();
    }

    /**
     * http://127.0.0.1:20040/sentinel/flow/E?paramA=1&paramB=2
     */
    @SentinelResource("/sentinel/flow/EE")
    @SneakyThrows(Exception.class)
    @GetMapping("flow/E")
    @ApiOperation("E")
    public Long flowE(@RequestParam(required = false) String paramA,
                      @RequestParam(required = false) String paramB) {
    
    
        // paramA in index 0, paramB in index 1.
        return RandomUtil.randomLong();
    }

    /**
     * http://127.0.0.1:20040/sentinel/F
     */
    @SneakyThrows(Exception.class)
    @GetMapping("F")
    @ApiOperation("F")
    public Long F() {
    
    
        return RandomUtil.randomLong();
    }

}

Today's sharing sentence:
In fact, all the efforts are not for others to see. Whether these efforts are meaningful depends on whether it has enriched your knowledge, strengthened your foundation, and transformed it into your ability. Efforts need to be productive, not look busy and hard.

Guess you like

Origin blog.csdn.net/qq_38225558/article/details/124844499