SpringBoot教程(三十二)| SpringBoot集成Sentinel

一、什么是Sentinel?

Sentinel 是阿里巴巴开源的一款流量控制、熔断降级的框架,能够帮助我们解决分布式系统中的流量管理问题。
主要用于微服务架构中的流量防护,提供限流、熔断、热点防护等机制

二、版本兼容性

  • Sentinel 通常与 Spring Cloud Alibaba 套件结合使用,需注意版本匹配。

点击 版本对应表 即可查看
我这边是SpringBoot 为 2.6.13,使用的 spring-cloud-alibaba-dependencies 即为 2021.0.5.0 版本

在这里插入图片描述

三、引入 Sentinel 核心依赖(以 Spring Cloud Alibaba 方式集成)

<!-- Spring Cloud Alibaba 版本管理(父工程或 dependencyManagement 中) -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2021.0.5.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<!-- Sentinel 核心依赖 -->
<dependencies>
    <!-- Spring Boot Web (用于测试接口) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- Sentinel 集成 Spring Cloud -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
</dependencies>

四、启动 Sentinel 控制台(服务端)

Sentinel 控制台用于可视化配置规则、监控流量,需单独启动:

步骤:
1.查看 sentinel 的版本
通过 spring-cloud-alibaba-dependencies 进行 查看,可以得出是 1.8.6
在这里插入图片描述

2.下载控制台 jar 包:从 Sentinel Releases 下载 sentinel-dashboard-${version}.jar。(我这里是 sentinel-dashboard-1.8.6.jar)
在这里插入图片描述

3.启动控制台:命令行执行(默认端口 8080,账号密码均为 sentinel):

java -jar sentinel-dashboard-1.8.6.jar --server.port=8080

4.访问控制台:浏览器打开 http://localhost:8080,输入账号密码登录。
在这里插入图片描述

在这里插入图片描述

五、Spring Boot 连接控制台

在 application.yml 中配置控制台地址:

server:
  port: 8080


spring:
  application:
    name: sentinel-demo  # 应用名称(控制台会显示此名称)
  cloud:
    sentinel:
      eager: true # 取消Sentinel控制台懒加载
      transport:
        dashboard: localhost:8085  # 控制台地址
        port: 8719  # 本地客户端与控制台通信的端口(默认8719,若被占用自动+1)

六、启动应用并触发资源注册

启动 Spring Boot 应用。
注意:Sentinel 默认是懒加载,资源首次被访问后才会在控制台显示,上面的配置我使用 eager: true 取消了懒加载
在这里插入图片描述

七、规则测试

1. 限流场景

限流场景(接口:/flow/{id})
核心逻辑:接口本身正常,仅当请求频率(QPS)超过阈值时被限流。

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SentinelDemoController {

    // ==================== 1. 限流场景 ====================
    /**
     * 限流测试接口:正常响应,仅通过QPS阈值触发限流
     * 资源名:flowLimitResource
     */
    @SentinelResource(
        value = "flowLimitResource",
        blockHandler = "flowBlockHandler" // 限流触发时的处理方法
    )
    @GetMapping("/flow/{id}")
    public String flowLimitTest(@PathVariable String id) {
        // 接口本身无异常,仅当QPS超过阈值时触发限流
        return "限流接口正常响应:" + id;
    }

    // 限流触发的处理方法(BlockException)
    public String flowBlockHandler(String id, BlockException e) {
        return "【限流触发】接口被限制,id=" + id + ",原因:" + e.getMessage();
    }
}

控制台配置(流控规则)
1.进入应用 → 流控规则 → 新增
2.资源名:flowLimitResource(与注解value一致)
3. 阈值类型:QPS → 单机阈值:2(每秒最多 2 次请求)
4.点击确定。

在这里插入图片描述

测试方法
快速刷新访问 http://localhost:8080/flow/1(1 秒内访问 3 次以上),会返回 flowBlockHandler 的限流提示。

在这里插入图片描述

2. 熔断场景

熔断场景(接口:/circuit/{id})
核心逻辑:接口固定超时(1 秒),当超时比例达标时,Sentinel 会暂时熔断接口(阻断请求)。

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SentinelDemoController {

    // ==================== 2. 熔断场景 ====================
    /**
     * 熔断测试接口:模拟高频超时,触发熔断规则
     * 资源名:circuitBreakResource
     */
    @SentinelResource(
        value = "circuitBreakResource",
        blockHandler = "circuitBlockHandler" // 熔断触发时的处理方法
    )
    @GetMapping("/circuit/{id}")
    public String circuitBreakTest(@PathVariable String id) throws InterruptedException {
        // 固定模拟超时(1秒),用于触发熔断规则的"慢调用比例"
        Thread.sleep(1000); // 强制睡眠1秒,超过熔断规则设置的RT阈值
        return "熔断接口正常响应:" + id;
    }

    // 熔断触发的处理方法(BlockException)
    public String circuitBlockHandler(String id, BlockException e) {
        return "【熔断触发】接口被熔断,id=" + id + ",原因:" + e.getMessage();
    }
}

控制台配置(熔断降级规则):
1.进入应用 → 熔断降级规则 → 新增
2.资源名:circuitBreakResource
3.熔断策略:慢调用比例
4.最大 RT(响应时间):500ms(超过 500ms 视为 “慢调用”)
5.慢调用比例阈值:0.5(50% 的请求是慢调用)
6.熔断时长:10s(熔断后 10 秒内直接阻断请求)
7.最小请求数:5(至少 5 次请求才判断是否熔断)
8.点击确定。

在这里插入图片描述

测试方法:
连续访问 http://localhost:8080/circuit/1 5 次以上(每次都会超时 1 秒,超过 500ms 阈值),当慢调用比例达到 50% 后,接口会被熔断,此时访问会返回 circuitBlockHandler 的熔断提示,10 秒后自动恢复。
在这里插入图片描述

3. 降级场景

降级场景(接口:/fallback/{id})
核心逻辑:当接口抛出业务异常时,通过fallback方法降级处理(与 Sentinel 规则无关,是业务自身的异常处理)。

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SentinelDemoController {

    // ==================== 3. 降级场景 ====================
    /**
     * 降级测试接口:主动抛出业务异常,触发fallback降级
     * 资源名:fallbackResource
     */
    @SentinelResource(
        value = "fallbackResource",
        fallback = "fallbackHandler" // 业务异常触发的降级方法
    )
    @GetMapping("/fallback/{id}")
    public String fallbackTest(@PathVariable String id) {
        // 当id为"error"时,主动抛出异常(固定触发条件)
        if ("error".equals(id)) {
            throw new RuntimeException("业务异常:id不能为'error'");
        }
        return "降级接口正常响应:" + id;
    }

    // 业务异常触发的降级处理方法
    public String fallbackHandler(String id, Throwable e) {
        return "【降级触发】业务异常处理,id=" + id + ",异常信息:" + e.getMessage();
    }
}

无需控制台配置:仅通过代码fallback参数指定处理方法。

测试方法:
1.访问 http://localhost:8080/fallback/normal → 正常响应(无异常)。
在这里插入图片描述

2.访问 http://localhost:8080/fallback/error → 触发RuntimeException,返回 fallbackHandler 的降级提示。
在这里插入图片描述

八、实现规则持久化

如果不配置数据源,当应用重启后,限流等配置信息都会丢失,需要再次重新配置,推荐使用nacos

方式一:通过 本地 JSON 文件

1. 配置 application.yml,指定本地文件路径

server:
  port: 8080

spring:
  application:
    name: sentinel-demo
  cloud:
    sentinel:
      eager: true  # 取消懒加载,启动时主动注册资源
      transport:
        dashboard: localhost:8085  # Sentinel控制台地址
        port: 8719  # 与控制台通信的端口
      datasource:
        # 流控规则:本地JSON文件数据源
        flow:
          file:  # 数据源类型为file
            file: classpath:sentinel/sentinel-flow-rules.json  # 本地JSON文件路径(resources目录下)
            rule-type: flow  # 规则类型:流控
            data-type: json  # 文件格式:JSON
            recommend-refresh-ms: 5000  # 官方自动刷新属性,单位毫秒(5秒检查一次文件变化)
        # 熔断规则:本地JSON文件数据源
        degrade:
          file:
            file: classpath:sentinel/sentinel-degrade-rules.json  # 熔断规则文件路径
            rule-type: degrade  # 规则类型:熔断
            data-type: json
            recommend-refresh-ms: 5000  # 自动刷新周期
  • classpath: 是类加载器的资源路径标识,在Maven 项目里,开发时指 src/main/resources,运行时指 target/classes

2. 在 resources/sentinel 目录下创建规则 JSON 文件

(1)流控规则文件:src/main/resources/sentinel/sentinel-flow-rules.json

[
  {
    "resource": "flowLimitResource",
    "grade": 1,
    "count": 2,
    "strategy": 0,
    "refResource": "",
    "controlBehavior": 0,
    "warmUpPeriodSec": 0,
    "maxQueueingTimeMs": 0,
    "clusterMode": false
  }
]

(2)流控规则文件:src/main/resources/sentinel/sentinel-degrade-rules.json

[
  {
    "resource": "circuitBreakResource",
    "grade": 0,
    "count": 500,
    "slowRatioThreshold": 0.5,
    "minRequestAmount": 5,
    "timeWindow": 10,
    "statIntervalMs": 1000
  }
]

在这里插入图片描述

方式二:通过 Nacos (推荐)

1. 下载nacos

1.查看 nacos 的版本
通过 spring-cloud-alibaba-dependencies 进行 查看,可以得出是 2.2.0
在这里插入图片描述
2.下载
nacos 官网:[https://nacos.io/docs/next/quickstart/quick-start/]
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2. 改成单机模式

因为 Nacos 默认以 “集群模式” 启动,所以需要先调整成单机模式
找到你 Nacos 的安装目录 → 进入 bin 文件夹
创建一个名为"单机模式"的bat脚本,内容如下

startup.cmd -m standalone

在这里插入图片描述

3. 进入naocs

请求地址:http://localhost:8848/nacos
账号密码都为:nacos
在这里插入图片描述
在这里插入图片描述

4. 配置nacos

在这里插入图片描述
sentinel流控规则数据源
Data ID:sentinel-demo-flow-rules
Group:DEFAULT_GROUP
配置格式:JSON

[
  {
    "resource": "flowLimitResource",
    "grade": 1,
    "count": 2,
    "strategy": 0,
    "refResource": "",
    "controlBehavior": 0,
    "warmUpPeriodSec": 0,
    "maxQueueingTimeMs": 0,
    "clusterMode": false
  }
]

参数说明:

  • “resource”: “flowLimitResource”, // 资源名:必须与代码中@SentinelResource(value)一致,对应/flow/{id}接口
  • “grade”: 1, // 限流阈值类型:1=QPS(每秒请求数),0=线程数(并发线程数)
  • “count”: 2, // 阈值:QPS=2(每秒最多允许2次请求)
  • “strategy”: 0, // 流控策略:0=直接(限制当前资源自身),1=关联,2=链路
  • “refResource”: “”, // 关联资源:仅strategy=1时生效,此处无需关联(留空)
  • “controlBehavior”: 0, // 控制行为:0=快速失败(超限时直接拒绝),1=预热,2=排队
  • “warmUpPeriodSec”: 0, // 预热时间:仅controlBehavior=1时生效(此处不生效)
  • “maxQueueingTimeMs”: 0, // 排队超时:仅controlBehavior=2时生效(此处不生效)
  • “clusterMode”: false // 集群限流:false=单机限流(仅限制当前应用实例)

在这里插入图片描述
sentinel熔断规则数据源
Data ID:sentinel-demo-degrade-rules
Group:DEFAULT_GROUP
配置格式:JSON

[
  {
    "resource": "circuitBreakResource",
    "grade": 0,
    "count": 500,
    "slowRatioThreshold": 0.5,
    "minRequestAmount": 5,
    "timeWindow": 10,
    "statIntervalMs": 1000
  }
]

参数说明:

  • “resource”: “circuitBreakResource”, // 资源名:与代码中@SentinelResource(value)一致,对应/circuit/{id}接口
  • “grade”: 0, // 熔断策略:0=慢调用比例(响应时间超过阈值的比例),1=异常比例,2=异常数
  • “count”: 500, // 阈值参数:grade=0时表示“最大RT(响应时间)”,单位ms(超过500ms视为慢调用)
  • “slowRatioThreshold”: 0.5, // 慢调用比例阈值:50%(慢调用数占总请求数的50%以上)
  • “minRequestAmount”: 5, // 最小请求数:统计周期内至少5次请求才判断是否熔断(避免少量请求误判)
  • “timeWindow”: 10, // 熔断时长:10秒(熔断后10秒内直接阻断请求)
  • “statIntervalMs”: 1000 // 统计时间窗口:1000ms=1秒(1秒内的请求纳入统计)

在这里插入图片描述

5. 修改yml配置

server:
  port: 8080  # 当前应用启动的端口号


spring:
  application:
    name: sentinel-demo  # 应用名称(Sentinel控制台和Nacos中会用此名称标识当前应用)
  cloud:
    sentinel:
      # 取消Sentinel控制台懒加载:默认情况下,Sentinel需要首次访问接口才会注册资源到控制台
      # 开启eager: true后,应用启动时就会主动注册资源,控制台能更快看到资源列表
      eager: true

      transport:
        dashboard: localhost:8085  # Sentinel控制台的地址(控制台启动的端口,需与控制台实际端口一致)
        port: 8719  # 本地应用与Sentinel控制台通信的端口(默认8719,若被占用会自动+1重试)

      # 配置Sentinel规则的数据源(将规则持久化到Nacos,避免重启丢失)
      datasource:
        # 1. 流控规则数据源(限制接口的请求频率/并发数)
        flow:
          nacos:  # 流控规则存储到Nacos
            server-addr: localhost:8848  # Nacos服务的地址(IP:端口)
            data-id: ${spring.application.name}-flow-rules  # Nacos中存储流控规则的配置文件名
            group-id: DEFAULT_GROUP  # Nacos中配置的分组(默认DEFAULT_GROUP即可)
            rule-type: flow  # 规则类型:flow表示这是流控规则(固定值)

        # 2. 熔断规则数据源(属于Sentinel的"降级规则",当接口不稳定时自动阻断请求)
        degrade:
          nacos:  # 熔断规则存储到Nacos
            server-addr: localhost:8848  # Nacos服务的地址
            data-id: ${spring.application.name}-degrade-rules  # Nacos中存储熔断规则的配置文件名
            group-id: DEFAULT_GROUP  # Nacos中配置的分组
            rule-type: degrade  # 规则类型:degrade表示这是熔断/降级规则(固定值)

6. 最终效果

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值