当前位置: 首页 > 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-service
uri: lb://user-service
predicates:
- Path=/user/**
filters:
- StripPrefix=1
- id: order-service
uri: lb://order-service
predicates:
- Path=/order/**
filters:
- StripPrefix=1
sentinel:
transport:
dashboard: localhost:8080  # Sentinel 控制台地址
port: 8719                  # 客户端心跳端口
scg:
fallback:
mode: response            # 降级响应模式
response-status: 429      # 限流响应状态码
response-body: '{"code":429,"msg":"请求过于频繁"}'  # 限流响应体
content-type: application/json
redirect: /fallback-page  # 重定向地址(可选)
server:
port: 10086

三、限流配置(Java 代码)

1. 路由维度限流(ResourceMode.ROUTE_ID)
@Configuration
public class RateLimitConfig {
@PostConstruct
public 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 {
@PostConstruct
public 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 {
@PostConstruct
public 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 {
@Override
public 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 {
@Override
public 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 {
@Bean
public 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:8848
file-extension: yaml
group: 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.jsqmd.com/news/321338/

相关文章:

  • 2025年当下靠谱的玻璃隔断定制排行,办公室隔断/雾化玻璃隔断/办公室隔断墙/电控玻璃隔断/感应门,玻璃隔断安装怎么选择
  • 基于python的交通信号灯检测识别系统
  • 快客之家产品好用吗,分析快客之家亮点有哪些
  • 多功能腻子喷涂机怎么选,普田喷涂机值得入手吗
  • 《透视 ImGui:从底层原理到面试通关》 第六讲:树形结构与弹出层 —— 复杂信息的组织
  • 浙江喷涂机制造商怎么选,普田喷涂机好用吗?
  • python基于协同过滤算法个性化动漫推荐系统hx3637
  • ABC432G Sum of Binom(A, B) 题解 / NTT
  • 2026年深圳靠谱的湿巾类包装企业排名,值得选的厂家汇总
  • 2026年口碑好的石墨烯发热片源头厂家推荐,专业制作企业全解析
  • 基于python的垃圾分类系统
  • 广雪制冷产品好用吗?价格怎样,探讨其合作报价与耐用性
  • C#联合CODESOFT标签在线列印软件,源代码,适合自己做二次开发标签在线列印软件。 里面可...
  • 基于python的凯特生活超市商品管理系统hx3940
  • 2026年定制眼镜品牌推荐,服务不错的定制眼镜品牌排名
  • 基于python的京东评论数据分析可视化
  • 基于python的连锁超市线上管理系统hx2008
  • 宁波郡狮全手工定制服装的口碑和价格咋样?
  • 2026江西中医药大学中医师承学习班口碑如何,真实评价全分享
  • 实用指南:腾讯WAIC发布“1+3+N”AI全景图:混元3D世界模型开源,具身智能平台Tairos亮相
  • 分析苏州众和,产品种类丰富吗?品牌形象好不好?为你揭晓答案
  • 开发电影/电视剧推荐工具,输入喜好类型,(悬疑/喜剧/言情)推荐适配作品,标注评分及看点,过滤烂片,帮用户节省选片的时间。
  • 2026年靠谱的聚氨酯喷涂机厂家,高效国产机品牌值得关注
  • 【面板数据】省级ZF公共服务注意力文本分析数据集(2000-2025)
  • 基于python的麻辣烫餐馆管理系统hx3543
  • C# Avalonia 19- DataBinding- DataTemplateList
  • 【工具变量】企业过度负债水平数据集(2009-2024年)
  • 物流冷库设计安装实力公司哪家好,广雪制冷值得选
  • 基于python的路面缺陷监测系统hx3052
  • 2026年杭州IPWO价格排名,节能效果好的产品怎么选