在微服务架构中,系统的稳定性至关重要。面对突发流量或恶意请求,若无有效防护机制,极易导致服务雪崩甚至系统崩溃。Sentinel 作为阿里巴巴开源的轻量级流量控制组件,能够帮助开发者快速实现限流、熔断、降级等容错能力。本文将聚焦于 Spring Boot 项目中整合 Sentinel,并基于 QPS(每秒查询数)进行限流 的完整实践。
QPS(Queries Per Second)即每秒请求数,是衡量系统处理能力的重要指标。QPS 限流 指的是当单位时间内请求超过设定阈值时,系统自动拒绝多余请求,从而保护后端服务不被压垮。
Sentinel 提供了多种限流模式,其中 直接模式 + QPS 阈值 是最常用的一种。
在 pom.xml 中引入 Sentinel 核心依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2022.0.0.0</version> <!-- 注意与 Spring Boot 版本兼容 -->
</dependency>若使用 Spring Cloud Alibaba,请确保版本匹配。也可单独引入
sentinel-core和sentinel-web-servlet,但推荐使用 starter 简化配置。
spring:
application:
name: sentinel-qps-demo
cloud:
sentinel:
transport:
dashboard: localhost:8080 # Sentinel 控制台地址(可选)
port: 8719 # 应用与 Dashboard 通信端口
eager: true # 是否在启动时立即初始化 Sentinel@RestController
public class TestController {
@GetMapping("/hello")
public String hello() {
return "Hello, Sentinel QPS Limit!";
}
}在启动类或配置类中添加初始化逻辑:
@PostConstruct
public void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("/hello"); // 资源名称,对应 URL
rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 限流模式:QPS
rule.setCount(2); // 阈值:每秒最多 2 次请求
rules.add(rule);
FlowRuleManager.loadRules(rules);
}注意:
@PostConstruct方法需放在被 Spring 管理的 Bean 中(如@Component或@Configuration类)。
http://localhost:8080/hello(例如使用 JMeter 或浏览器快速刷新)。FlowException,默认返回 HTTP 500。可通过实现 UrlBlockHandler 自定义拒绝策略:
@Component
public class CustomUrlBlockHandler implements UrlBlockHandler {
@Override
public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().write("{\"code\":429,\"msg\":\"请求过于频繁,请稍后再试!\"}");
}
}注意:在较新版本中,可通过
WebCallbackManager设置全局 block handler:
@PostConstruct
public void initBlockHandler() {
WebCallbackManager.setUrlBlockHandler(new CustomUrlBlockHandler());
}http://localhost:8080/hello 资源,点击「流控」按钮优势:动态调整限流规则,实时生效,适合生产环境
/hello),也可通过 @SentinelResource 自定义资源名。通过 Spring Boot 与 Sentinel 的无缝集成,我们能够以极低的成本为系统加上“流量阀门”。QPS 限流作为最基础也是最有效的防护手段,能有效防止突发流量冲击,保障核心服务稳定运行。结合 Sentinel Dashboard,更可实现规则的动态管理与实时监控,是构建高可用微服务架构的必备利器。
小提示:限流只是容错体系的一环,建议配合熔断、降级、系统自适应保护等策略,构建全方位的韧性系统。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。