spring sentinel

发布于:2025-05-30 ⋅ 阅读:(34) ⋅ 点赞:(0)

sentinel文档 introduction | Sentinel

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>dr.cqr</groupId>
    <artifactId>demor</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <java.version>1.8</java.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.13.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!--核心包-->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-core</artifactId>
            <version>1.8.8</version>
        </dependency>
        <!--控制台 https://objects.githubusercontent.com/github-production-release-asset-2e65be/128018428/de5472a3-9b33-490c-bbc9-d7488457a9f3?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=releaseassetproduction%2F20250523%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250523T025314Z&X-Amz-Expires=300&X-Amz-Signature=ab429931545643976133acb9963f0a716d207bb36a55fe6ab5dd1a647a6e44a0&X-Amz-SignedHeaders=host&response-content-disposition=attachment%3B%20filename%3Dsentinel-dashboard-1.8.8.jar&response-content-type=application%2Foctet-stream-->
        <!-- 客户端需要引入 Transport 模块来与 Sentinel 控制台进行通信 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-transport-simple-http</artifactId>
            <version>1.8.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba.csp/sentinel-annotation-aspectj -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-annotation-aspectj</artifactId>
            <version>1.8.8</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-starter-alibaba-sentinel -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
    </dependencies>
    <dependencyManagement>

    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.yml

server:
  port: 19610
  tomcat:
    connection-timeout: 300000

spring:
  profiles:
    active: dev
  application:
    name: demor
    datasource:
      url: jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
  cloud:
    sentinel:
      transport:
        dashboard: 192.168.1.18:9999 # 控制台地址

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

控制器

package dr.cqr.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

// https://sentinelguard.io/zh-cn/docs/circuit-breaking.html
@RestController
@RequestMapping("/test")
public class Test {

    @GetMapping("/t")
    public String tt () throws InterruptedException {
        return "ok";
    }

    // 流量控制 配置规则.
    // 抛出FlowException
    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        // 资源名,即限流规则的作用对象
        rule.setResource("HelloWorld");
        // 流量控制主要有两种统计类型,一种是统计线程数,另外一种则是统计 QPS
        // 限流阈值类型,QPS 或线程数
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        // 限流阈值
        rule.setCount(10);
        // 流量控制的手段
        // 直接拒绝(RuleConstant.CONTROL_BEHAVIOR_DEFAULT)方式。该方式是默认的流量控制方式
        // 冷启动(RuleConstant.CONTROL_BEHAVIOR_WARM_UP)方式
        // 匀速器(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)方式。这种方式严格控制了请求通过的间隔时间,也即是让请求以均匀的速度通过,对应的是漏桶算法。
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);

        // 根据调用方限流
        // default:表示不区分调用者
        // {some_origin_name}:表示针对特定的调用者,只有来自这个调用者的请求才会进行流量控制
        // other:表示针对除 {some_origin_name} 以外的其余调用方的流量进行流量控制
        // 同一个资源名可以配置多条规则,规则的生效顺序为:{some_origin_name} > other > default
        rule.setLimitApp("default");

        // 排队时间为2秒
        rule.setMaxQueueingTimeMs(2 * 1000);

        // 关闭预热 默认10
        rule.setWarmUpPeriodSec(0);

        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    // Block 异常处理函数,参数最后多一个 BlockException,其余与原函数一致.
    public String blockHandlers(String name, BlockException ex){
        // 处理被流控的逻辑
        System.out.println("BlockException blocked! 2");
        System.out.println(ex);
        System.out.println(name);
        return "BlockException blocked! 2";
    }

    // Fallback 函数,函数签名与原函数一致或加一个 Throwable 类型的参数.
    public String fallbackHandlers(Throwable ex){
        // 处理被流控的逻辑
        System.out.println("fallbackHandlers blocked! 2");
        System.out.println(ex);
        return "fallbackHandlers blocked! 2";
    }

    @GetMapping("/helloWorld")
    public String helloWorld () {
        // 配置规则.
        initFlowRules();

        // 1.5.0 版本开始可以直接利用 try-with-resources 特性
        try (Entry entry = SphU.entry("HelloWorld")) {
            // 被保护的逻辑
            System.out.println("hello world");
        } catch (BlockException ex) {
            // 处理被流控的逻辑
            System.out.println("blocked!");
        }


        return "ok";
    }


    // 注解方式
    // 如果该接口的流量超过设定的阈值,则会触发限流,进而调用 handleBlock 方法。
    // blockHandler:当流量控制或熔断降级触发时,会调用该方法,返回对应的提示信息。
    // blockHandler 函数会在原方法被限流/降级/系统保护的时候调用,
    // 而 fallback 函数会针对所有类型的异常。
    // 请注意 blockHandler 和 fallback 函数的形式要求,更多指引可以参见 Sentinel 注解支持文档。
    // 若 blockHandler 和 fallback 都进行了配置,则被限流降级而抛出 BlockException 时只会进入 blockHandler 处理逻辑。
    // 若未配置 blockHandler、fallback 和 defaultFallback,则被限流降级时会将 BlockException 直接抛出。
    @GetMapping("/helloWorld2")
    @SentinelResource(value = "HelloWorld", blockHandler = "blockHandlers", fallback = "fallbackHandlers")
    public String helloWorld2 (String name)  {
        // 资源中的逻辑
        System.out.println("hello world2");

        return "ok";
    }










}

控制台启动参数

java -Dserver.port=9999 
-Dcsp.sentinel.dashboard.server=localhost:9999 
-Dproject.name=sentinel-dashboard 
-Dsentinel.dashboard.auth.username=admin 
-Dsentinel.dashboard.auth.password=654321 
-Dserver.servlet.session.timeout=7200 
-jar sentinel-dashboard-1.8.8.jar