精心整理了最新的面试资料和简历模板,有需要的可以自行获取
SpringBoot整合Sentinel实现流量控制与熔断降级
一、简介
Sentinel 是阿里巴巴开源的分布式系统流量控制组件,支持流量控制、熔断降级、系统保护等功能。与SpringBoot集成后,可以快速实现微服务架构中的服务稳定性保障。
二、环境准备
- JDK 1.8+
- Spring Boot 2.7.x
- Sentinel 1.8.6
- Sentinel Dashboard(控制台)
三、整合步骤
1. 创建SpringBoot项目
通过 start.spring.io 创建基础项目,选择以下依赖:
- Spring Web
- Actuator
2. 添加Sentinel依赖
<!-- pom.xml -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2021.0.5.0</version>
</dependency>
3. 配置application.yml
spring:
application:
name: sentinel-demo
cloud:
sentinel:
transport:
dashboard: localhost:8080 # Sentinel控制台地址
port: 8719 # 本地启动的HTTP Server端口
eager: true # 立即初始化
management:
endpoints:
web:
exposure:
include: '*'
四、安装Sentinel Dashboard
- 下载 sentinel-dashboard-1.8.6.jar
- 启动控制台:
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -jar sentinel-dashboard-1.8.6.jar
- 访问
http://localhost:8080
(默认账号密码:sentinel/sentinel)
五、编写示例接口
@RestController
public class DemoController {
@GetMapping("/test")
@SentinelResource(value = "test", blockHandler = "handleBlock")
public String test() {
return "Hello Sentinel!";
}
// 限流/降级处理逻辑
public String handleBlock(BlockException ex) {
return "请求被限流,请稍后重试!";
}
}
六、配置流量控制规则
1. 通过控制台配置
- 访问Sentinel Dashboard
- 在「簇点链路」找到
/test
接口 - 点击「流控」按钮,设置QPS阈值为2(每秒最多2次请求)
2. 通过代码配置(可选)
@PostConstruct
public void initRule() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("test");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(2);
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
七、熔断降级示例
@GetMapping("/order")
@SentinelResource(
value = "orderService",
fallback = "fallbackHandler",
blockHandler = "blockHandler"
)
public String getOrder() {
// 模拟业务异常
if (System.currentTimeMillis() % 2 == 0) {
throw new RuntimeException("业务异常");
}
return "订单查询成功";
}
// 熔断降级处理
public String fallbackHandler(Throwable ex) {
return "服务暂时不可用:" + ex.getMessage();
}
// 流量控制处理
public String blockHandler(BlockException ex) {
return "请求过于频繁,请稍后再试";
}
八、高级配置
1. 自定义异常返回
@Configuration
public class SentinelConfig {
@PostConstruct
public void init() {
WebCallbackManager.setUrlBlockHandler((request, response, ex) -> {
response.getWriter().print(JSON.toJSONString(
Map.of("code": 429, "msg": "自定义限流提示")));
});
}
}
2. 持久化配置(需配合Nacos)
spring:
cloud:
sentinel:
datasource:
ds1:
nacos:
server-addr: localhost:8848
dataId: sentinel-rules
groupId: DEFAULT_GROUP
rule-type: flow
九、测试验证
- 启动SpringBoot应用
- 访问接口触发流量
# 使用压测工具验证 ab -n 100 -c 10 http://localhost:8080/test
- 观察控制台实时监控数据
十、注意事项
- 确保客户端与控制台网络连通
- 生产环境建议配置规则持久化
- 熔断规则需要足够的请求量才能触发
- 注意区分
blockHandler
(流量控制)和fallback
(业务异常)
十一、总结
通过本文实现了:
- Sentinel基础整合
- 流量控制配置
- 熔断降级策略
- 自定义异常处理
- 控制台监控
官方文档推荐:Sentinel官方文档
Q&A
Q: 控制台看不到应用?
A: 确保客户端已发送心跳(访问一次接口即可)
Q: 规则不生效?
A: 检查资源名是否匹配,规则类型是否正确
可以根据实际需求扩展更多功能:热点参数限流、系统保护规则、网关流控等。