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

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

相关推荐
欢醉6 天前
踩坑记:一次Nacos客户端偶发connect timed out全链路排查
nacos·springcloud
ChaITSimpleLove6 天前
云原生性能对决:JDK21虚拟线程+GraalVM vs .NET10/11 技术栈深度对比
微服务·云原生·serverless·graalvm native·native aot·runtime async·.net11/java21
EatFan7 天前
gRPC 为什么比 HTTP+JSON 快?详细讲解gRPC
后端·微服务·grpc
小小谈电商7 天前
大型集团级 B2B2C 商城落地|微服务高并发电商系统实践复盘
springcloud·商城源码选型·微服务电商·b2b2c商城·集团电商
辛迪聊物业数字化8 天前
智慧物业管理平台架构实践:从SaaS物业云到商管系统的全模块落地
大数据·微服务·php
叶总没有会8 天前
Nacos—注册中心
spring cloud·微服务
天天喝旺仔8 天前
分布式服务容错实战:用 Sentinel 实现限流、熔断与降级
分布式·微服务·云原生·sentinel
jonyleek9 天前
企业文档私有化实践:基于JVS数字底座的可控协同架构设计与落地要点
elasticsearch·私有化部署·springcloud·微服务架构·信创适配·jvs·企业文档
周先生FullStack9 天前
Mac + 容器本地 MySQL/Redis 环境搭建与网络原理实战
java·spring boot·微服务·容器·架构·个人开发
叶总没有会9 天前
微服务--分布式基础
java·spring·spring cloud·微服务