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
  • 限流方式:按参数
  • 参数1type=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 保护微服务

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

相关推荐
却话巴山夜雨时i13 小时前
互联网大厂Java面试场景:Spring Boot、微服务与Redis实战解析
spring boot·redis·微服务·kafka·prometheus·java面试·电商场景
星梦清河14 小时前
01 微服务
微服务·云原生·架构
迷藏49415 小时前
**发散创新:基于角色与属性的混合权限模型在微服务架构中的实战落地**在现代分布式系统中,
java·python·微服务·云原生·架构
晏宁科技YaningAI17 小时前
分布式通信系统的容错机制
网络协议·微服务·系统架构·gateway·信息与通信·paas
yzp-18 小时前
Sentinel 执行流程
sentinel
星河耀银海1 天前
远控体验分享:安全与实用性参考
人工智能·安全·微服务
宠友信息1 天前
一套基于uniapp+springboot完整社区系统是如何实现的?友猫社区源码级功能解析
java·spring boot·后端·微服务·微信·uni-app
全栈开发圈1 天前
新书速览|从零开始学Spring Cloud微服务架构
spring cloud·微服务·架构
亚历克斯神1 天前
Spring Cloud 2026 架构演进
java·spring·微服务
沃尔威武2 天前
微服务架构下:如何用gRPC实现跨语言高效通信
微服务·云原生·架构