Spring Cloud Alibaba 实战:Sentinel 保障微服务的高可用性与流量防护

1.1 Sentinel 作用

Sentinel 是阿里巴巴开源的一款 流量控制和熔断降级 框架,主要用于:

  • 流量控制:限制 QPS,防止流量暴增导致系统崩溃
  • 熔断降级:当某个服务不可用时自动降级,避免故障扩散
  • 热点参数限流:根据参数值进行精细化流控(例如 VIP 用户限流策略)
  • 系统自适应保护:根据系统负载自动调整限流规则
  • 授权规则:根据来源服务进行限流
  • API 网关防护:结合 Spring Cloud Gateway 保护微服务

1.2 Sentinel 核心概念

概念 说明
资源 (Resource) 需要保护的代码逻辑(如方法、API)
规则 (Rule) 限流、熔断等策略
流控 (Flow Control) 限制 QPS、线程数等
熔断 (Circuit Breaker) 基于响应时间或错误比率触发熔断
热点限流 (Hot Param Flow) 针对特定参数进行限流
系统规则 (System Rule) 保护系统整体资源
授权规则 (Authority Rule) 根据请求来源控制访问

2. 引入 Sentinel 依赖

在 pom.xml 中添加 Sentinel 依赖:

java 复制代码
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

Spring Boot 自动整合 Sentinel,无需额外配置。


3. 启动 Sentinel 控制台

3.1 下载并运行 Sentinel 控制台

  1. 下载 Sentinel Dashboard

    java 复制代码
    wget https://github.com/alibaba/Sentinel/releases/download/1.8.6/sentinel-dashboard-1.8.6.jar
  2. 启动控制台

    java 复制代码
    java -jar sentinel-dashboard-1.8.6.jar
  3. 访问 Sentinel 控制台

    1. URL: http://localhost:8080
    2. 默认账号:sentinel
    3. 默认密码:sentinel

4. 配置 Sentinel

在 application.yml 添加 Sentinel 连接控制台:

java 复制代码
spring:
  application:
    name: sentinel-demo
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719  # 本地 Sentinel 客户端通信端口

这样,Sentinel 客户端会自动向控制台注册。


5. 流量控制

流控规则可以基于 QPS 、线程数 等方式进行限流。

5.1 代码示例

在 SentinelController.java 创建受保护的接口:

java 复制代码
@RestController
public class SentinelController {

    @GetMapping("/test")
    @SentinelResource(value = "testResource", blockHandler = "handleBlock")
    public String test() {
        return "Hello Sentinel";
    }

    // 限流时的处理方法
    public String handleBlock(BlockException ex) {
        return "请求被限流";
    }
}

5.2 配置流控规则

在 Sentinel 控制台 添加流控规则:

  • 资源名称 :testResource
  • 流控模式:QPS
  • 阈值:1(超过 1 QPS 就触发限流)
  • 流控效果:直接拒绝

测试:

java 复制代码
ab -n 10 -c 2 http://localhost:8080/test

如果请求过多,就会返回 "请求被限流"。


6. 熔断降级

Sentinel 支持基于:

  1. RT(响应时间):如果平均响应时间超过阈值,就会熔断。
  2. 异常比例:如果异常请求占比超过阈值,就会熔断。
  3. 异常数:一定时间内异常数超过阈值,就会熔断。

6.1 代码示例

java 复制代码
@RestController
public class CircuitBreakerController {

    @GetMapping("/slow")
    @SentinelResource(value = "slowService", fallback = "fallbackMethod")
    public String slowService() throws InterruptedException {
        Thread.sleep(2000);
        return "Slow Service";
    }

    // 降级处理
    public String fallbackMethod(Throwable t) {
        return "降级:服务不可用";
    }
}

6.2 Sentinel 控制台配置

  • 资源名称 :slowService
  • 熔断策略:响应时间
  • RT 阈值:1000ms(如果超过 1s,就会熔断)

7. 热点参数限流

针对某个 URL 参数进行限流,例如:

java 复制代码
@RestController
public class HotParamController {

    @GetMapping("/paramLimit")
    @SentinelResource(value = "hotParam", blockHandler = "handleHotParam")
    public String hotParam(@RequestParam String type) {
        return "Access type: " + type;
    }

    public String handleHotParam(String type, BlockException ex) {
        return "请求被限流:" + type;
    }
}

Sentinel 控制台配置

  • 资源名称 :hotParam
  • 限流方式:按参数
  • 参数1 :type=vip,QPS 限制 1

测试:

java 复制代码
curl "http://localhost:8080/paramLimit?type=vip"

8. 结合 Nacos 进行规则动态推送

在 application.yml 配置:

java 复制代码
spring:
  cloud:
    sentinel:
      datasource:
        flow:
          nacos:
            server-addr: localhost:8848
            data-id: sentinel-rules
            group-id: DEFAULT_GROUP
            rule-type: flow

在 Nacos 配置 sentinel-rules:

java 复制代码
[
  {
    "resource": "testResource",
    "limitApp": "default",
    "grade": 1,
    "count": 2,
    "strategy": 0,
    "controlBehavior": 0
  }
]

这样 Sentinel 规则可以动态调整,无需重启服务。


9. 监控 API 网关

Sentinel 结合 Spring Cloud Gateway 保护 API 网关:

java 复制代码
spring:
  cloud:
    gateway:
      routes:
        - id: service1
          uri: lb://service1
          predicates:
            - Path=/service1/**
          filters:
            - name: Sentinel

在 Sentinel 控制台可以查看 API 访问流量。


10. 总结

功能 说明
流量控制 限制 QPS、线程数,防止瞬时流量过载
熔断降级 避免错误扩散,提高系统稳定性
热点限流 只对特定参数进行限流
动态规则 结合 Nacos 实现规则热更新
API 网关保护 结合 Spring Cloud Gateway 保护微服务

🔥 如果这篇文章有帮助,欢迎 点赞、收藏、评论,你的支持是我持续更新的动力!🚀

相关推荐
露天赏雪18 小时前
第3篇:Sentinel熔断降级实战:大模型接口抖动时的服务兜底方案
java·开发语言·人工智能·spring boot·spring·servlet·sentinel
wdyan2971 天前
带着小白学习-微服务-5 实战:配置中心-数据库连接
数据库·学习·微服务
胡写代码2 天前
把数据库连接搬进配置中心,服务起不来:spring.config.import 的 4 个必填项
spring cloud·微服务
利威尔xu5 天前
Go IM 源码实战(14):本地缓存快 3000 倍,失效却难 10 倍
后端·缓存·微服务·面试·golang
利威尔xu5 天前
Go IM 源码实战(13):30 个会话只有 2 个红点,未读数错在三条路径
redis·后端·微服务·面试·golang
骑着蜗牛撵大象3275 天前
Spring Boot 4.1 + Spring AI 2.0:RAG 供文、图谱供关系、MCP 供工具的 Java Agent 平台
java·spring boot·spring·微服务·知识图谱·rag·mcp
code_slave(码畜)5 天前
微服务架构落地:慢 SQL 治理与连接池调优 —— 守住数据库的最后一道防线
数据库·spring boot·sql·spring cloud·微服务·架构
欢醉5 天前
前后端Long精度丢失的踩坑
springboot·springcloud
微三云 - 廖会灵 (私域系统开发)7 天前
企业级 SaaS 系统架构设计:单体、微服务还是模块化单体?技术选型实战
微服务·架构·系统架构
shuair7 天前
Spring Cloud 微服务脚手架:Simple Cloud 系统架构设计
spring cloud·微服务·系统架构