【微服务知识】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
八、监控查看
- 访问 Sentinel 控制台
http://localhost:8080 - 查看实时监控:
- 流控规则:
流控规则 -> 网关流控 - 熔断规则:
熔断降级 -> 熔断规则 - 实时QPS:
簇点链路 -> /user/**
- 流控规则:
九、完整项目结构
src/main/java
├── config
│ ├── CircuitBreakerConfig.java # 熔断配置
│ ├── RateLimitConfig.java # 限流配置
│ └── GlobalExceptionHandler.java # 全局异常处理
├── controller
│ └── ApiController.java # 测试接口
└── GatewayApplication.java # 启动类
十、注意事项
- 版本兼容性:确保 Spring Cloud 版本与 Sentinel 版本匹配(如 2020.0.x + Sentinel 1.8.x)
- 线程安全:动态规则配置需注意并发修改问题
- 性能调优:根据实际业务调整
controlBehavior(如匀速排队模式) - 日志监控:建议开启 Sentinel 日志
logging.level.com.alibaba.csp.sentinel=DEBUG
通过以上配置,可实现网关层的精细化流量控制与容错机制,保障系统稳定性。
相关文献
【springboot知识】配置方式实现SpringCloudGateway相关功能
【Spring知识】springcloud相关技术栈组件
【后端知识】服务治理组件Sentinel快速入门
