当前位置: 首页 > news >正文

【微服务知识】SpringCloudGateway结合Sentinel实现服务的限流,熔断与降级

SpringCloudGateway结合Sentinel实现服务的限流,熔断与降级

      • 一、依赖配置(pom.xml)
      • 二、配置文件(application.yml)
      • 三、限流配置(Java 代码)
        • 1. 路由维度限流(ResourceMode.ROUTE_ID)
        • 2. 自定义 API 分组限流(ResourceMode.CUSTOM_API_NAME)
      • 四、熔断降级配置
        • 1. 异常比例熔断(DegradeRule)
        • 2. 慢调用熔断
      • 五、降级响应自定义
        • 1. 限流降级处理器
        • 2. 熔断降级处理器
        • 3. 全局异常处理器
      • 六、动态规则配置(Nacos)
        • 1. 添加依赖
        • 2. 配置文件
        • 3. Nacos 规则配置示例
      • 七、测试验证
        • 1. 限流测试
        • 2. 熔断测试
      • 八、监控查看
      • 九、完整项目结构
      • 十、注意事项
    • 相关文献

以下是 Spring Cloud Gateway 结合 Sentinel 实现服务限流、熔断和降级的完整代码及配置方案,整合了限流规则配置、熔断策略、自定义降级响应等核心功能:

一、依赖配置(pom.xml)

<dependencies><!-- Spring Cloud Gateway --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!-- Sentinel 适配 Gateway --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId><version>2.2.9.RELEASE</version></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId><version>2.2.9.RELEASE</version></dependency><!-- Nacos 数据源(可选动态规则配置) --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency>
</dependencies>

二、配置文件(application.yml)

spring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/user/**filters:- StripPrefix=1- id: order-serviceuri: lb://order-servicepredicates:- Path=/order/**filters:- StripPrefix=1sentinel:transport:dashboard: localhost:8080  # Sentinel 控制台地址port: 8719                  # 客户端心跳端口scg:fallback:mode: response            # 降级响应模式response-status: 429      # 限流响应状态码response-body: '{"code":429,"msg":"请求过于频繁"}'  # 限流响应体content-type: application/jsonredirect: /fallback-page  # 重定向地址(可选)server:port: 10086

三、限流配置(Java 代码)

1. 路由维度限流(ResourceMode.ROUTE_ID)
@Configuration
public class RateLimitConfig {@PostConstructpublic void init() {Set<GatewayFlowRule> rules = new HashSet<>();// 针对 user-service 路由限流(QPS 限制为 10)rules.add(new GatewayFlowRule("user-service").setCount(10).setIntervalSec(1).setGrade(RuleConstant.FLOW_GRADE_QPS).setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT));// 针对 order-service 路由限流(线程数限制为 20)rules.add(new GatewayFlowRule("order-service").setCount(20).setIntervalSec(1).setGrade(RuleConstant.FLOW_GRADE_THREAD).setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT));GatewayRuleManager.loadRules(rules);}
}
2. 自定义 API 分组限流(ResourceMode.CUSTOM_API_NAME)
@Configuration
public class CustomApiRateLimitConfig {@PostConstructpublic void init() {Set<GatewayFlowRule> rules = new HashSet<>();// 定义 API 分组 /api/v1/**rules.add(new GatewayFlowRule("v1-api-group").setCount(50).setIntervalSec(10).setGrade(RuleConstant.FLOW_GRADE_QPS).setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME).setParamItem(new ParamFlowItem().setParseStrategy(ParamFlowItem.ParseStrategy.URL_PARAM).setFieldName("userId").setPattern("^[0-9]+$")));  // 仅对数字参数生效GatewayRuleManager.loadRules(rules);}
}

四、熔断降级配置

1. 异常比例熔断(DegradeRule)
@Configuration
public class CircuitBreakerConfig {@PostConstructpublic void init() {DegradeRule degradeRule = new DegradeRule("order-service").setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO)  // 异常比例模式.setCount(0.5)  // 异常比例阈值(50%).setTimeWindow(10)  // 统计时间窗口(秒).setMinRequestAmount(10)  // 最小请求数.setStatIntervalMs(1000);  // 统计间隔DegradeRuleManager.loadRules(Collections.singletonList(degradeRule));}
}
2. 慢调用熔断
// 在配置类中添加
DegradeRule slowRule = new DegradeRule("user-service").setGrade(RuleConstant.DEGRADE_GRADE_RT)  // 慢调用比例.setCount(3000)  // RT 阈值(毫秒).setTimeWindow(10).setMinRequestAmount(5);
DegradeRuleManager.loadRules(Collections.singletonList(slowRule));

五、降级响应自定义

1. 限流降级处理器
@Component
public class RateLimitFallbackHandler implements BlockRequestHandler {@Overridepublic Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {Map<String, Object> result = new HashMap<>();result.put("code", 429);result.put("msg", "系统繁忙,请稍后重试");return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS).contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(result));}
}
2. 熔断降级处理器
@Component
public class DegradeFallbackHandler implements BlockRequestHandler {@Overridepublic Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {Map<String, Object> result = new HashMap<>();result.put("code", 503);result.put("msg", "服务暂时不可用");return ServerResponse.status(HttpStatus.SERVICE_UNAVAILABLE).contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(result));}
}
3. 全局异常处理器
@Configuration
public class GlobalExceptionHandler {@Beanpublic SentinelGatewayBlockExceptionHandler sentinelBlockExceptionHandler(SentinelGatewayFilter sentinelGatewayFilter,List<ViewResolver> viewResolvers,ServerCodecConfigurer serverCodecConfigurer) {return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer) {@Overrideprotected Mono<Void> writeResponse(ServerWebExchange exchange, ServerResponse response) {// 自定义日志记录log.error("Sentinel拦截异常: {}", response.statusCode());return super.writeResponse(exchange, response);}};}
}

六、动态规则配置(Nacos)

1. 添加依赖
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
2. 配置文件
spring:cloud:nacos:config:server-addr: localhost:8848file-extension: yamlgroup: SENTINEL_GROUP
3. Nacos 规则配置示例
# 流量控制规则
spring.cloud.sentinel.datasource.ds1.nacos.server-addr=localhost:8848
spring.cloud.sentinel.datasource.ds1.nacos.data-id=${spring.application.name}-flow-rules
spring.cloud.sentinel.datasource.ds1.nacos.rule-type=flow# 熔断规则
spring.cloud.sentinel.datasource.ds2.nacos.data-id=${spring.application.name}-degrade-rules
spring.cloud.sentinel.datasource.ds2.nacos.rule-type=degrade

七、测试验证

1. 限流测试
# 使用 Apache Benchmark 发送高频请求
ab -n 100 -c 10 http://localhost:10086/user/info
2. 熔断测试
// 模拟异常请求
for i in {1..100}; do curl -X POST http://localhost:10086/order/create -d '{}'; done

八、监控查看

  1. 访问 Sentinel 控制台 http://localhost:8080
  2. 查看实时监控:
    • 流控规则流控规则 -> 网关流控
    • 熔断规则熔断降级 -> 熔断规则
    • 实时QPS簇点链路 -> /user/**

九、完整项目结构

src/main/java
├── config
│   ├── CircuitBreakerConfig.java    # 熔断配置
│   ├── RateLimitConfig.java         # 限流配置
│   └── GlobalExceptionHandler.java  # 全局异常处理
├── controller
│   └── ApiController.java           # 测试接口
└── GatewayApplication.java          # 启动类

十、注意事项

  1. 版本兼容性:确保 Spring Cloud 版本与 Sentinel 版本匹配(如 2020.0.x + Sentinel 1.8.x)
  2. 线程安全:动态规则配置需注意并发修改问题
  3. 性能调优:根据实际业务调整 controlBehavior(如匀速排队模式)
  4. 日志监控:建议开启 Sentinel 日志 logging.level.com.alibaba.csp.sentinel=DEBUG

通过以上配置,可实现网关层的精细化流量控制与容错机制,保障系统稳定性。

相关文献

【springboot知识】配置方式实现SpringCloudGateway相关功能

【Spring知识】springcloud相关技术栈组件

【后端知识】服务治理组件Sentinel快速入门

http://www.dtcms.com/a/596699.html

相关文章:

  • Python基础教学:Python中enumerate函数的使用方法-由Deepseek产生
  • 算法基础篇:(六)基础算法之双指针 —— 从暴力到高效的优化艺术
  • 家庭网络搭建网站做网站能赚钱吗 知乎
  • 江苏省住房与城乡建设厅网站首页广告网站建设报价
  • HarmonyOS状态管理精细化:控制渲染范围与变量拆分策略
  • win32k!ProcessKeyboardInputWorker函数和win32k!xxxProcessKeyEvent函数分析键盘扫描码和vk码
  • k均值,密度聚类,层次聚类三种聚类底层逻辑的区别
  • 基于微信小程序的茶叶茶具销售和管理系统(源码+论文+部署+安装)
  • INT303 Big Data Analysis 大数据分析 Pt.8 聚类
  • 4-ARM-PEG-Biotin(2)/Silane(2),特性与制备方法解析
  • 【成功案例】朗迪锋助力高校实验室数智化升级
  • 【开题答辩实录分享】以《证劵数据可视化分析项目设计与实现》为例进行答辩实录分享
  • 可信计算、TPM
  • SAP HANA 发展历史:内存计算如何重塑企业级数据平台
  • 存算一体架构在空间计算中的应用
  • docker swarm集群搭建,对比k8s
  • 为什么网站需要维护需要网站建设
  • 25年05月架构甄选范文“论多模型数据源”,软考高级,系统架构设计师论文
  • 重庆做网站公司哪家比较好图片设计在线
  • Ubuntu 上使用 VSCode 调试 C++ (CMake 项目) 指南
  • opencv 学习: 07 使用迭代器 (iterator) 遍历像素
  • Two Sigma 面经分享|智商检测级别的面试,逻辑与细节缺一不可
  • 【STM32项目开源】STM32单片机物联网门禁控制系统
  • Ubuntu 系统部署 PostgreSQL 主从复制 + 流复制(Streaming Replication)完整操作指南
  • 福州企业网站推广定制wordpress国人模板
  • 场景落地绘就创新图景,人工智能迎来应用浪潮
  • 数据结构(20)
  • 线性代数 - 理解求解矩阵特征值的特征方程
  • Swift的逃逸闭包
  • ESP32基础-GPIO_LED进阶