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 保护微服务

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

相关推荐
像少年啦飞驰点、3 分钟前
零基础入门 Spring Boot:从“Hello World”到可部署微服务的完整学习路径
java·spring boot·微服务·编程入门·后端开发
java干货23 分钟前
微服务:把一个简单的问题,拆成 100 个网络问题
网络·微服务·架构
indexsunny1 小时前
互联网大厂Java求职面试实战:Spring Boot微服务与Kafka消息队列应用解析
java·数据库·spring boot·微服务·面试·kafka·jpa
天才奇男子2 小时前
《深度解析HAProxy七层代理:原理、配置与最佳实践》
linux·运维·微服务·云原生
onkel in blog3 小时前
【Java】Gradle 多模块项目实战:Spring Boot 微服务搭建全流程
java·spring boot·微服务·gradle
七夜zippoe3 小时前
Kubernetes与Python微服务编排实战:从基础部署到自动扩缩容
python·微服务·kubernetes·service·hpa
小楼v3 小时前
使用Nacos实现动态IP黑名单过滤
java·后端·微服务·nacos
JavaLearnerZGQ4 小时前
Gateway网关将登录用户信息传递给下游微服务(完整实现方案)
微服务·架构·gateway
麦聪聊数据20 小时前
利用SQL2API模式重构微服务中的数据查询层
数据库·sql·低代码·微服务·架构
九皇叔叔1 天前
【03】微服务系列 之Nacos 注册中心(服务注册)
java·微服务·nacos·架构·注册中心·服务注册