SpringBoot集成Sentinel实战:从依赖到自定义限流与监控

360影视 动漫周边 2025-05-06 10:51 6

摘要:@RestController@requestMapping("/pilot")public class PilotController {@SentinelResource(value = "pilot_list", blockHandler = "bloc

com.alibaba.cloudspring-cloud-starter-alibaba-Sentinel2.2.10-RC1

groupId也可为 org.springframework.cloud。

我使用的 JDK23+SpringBoot3.4.1:

com.alibaba.cloudspring-cloud-starter-alibaba-sentinel2023.0.3.22 暴露端点

整合成功后,会暴露actuator/Sentinel端点,所以再添依赖:

org.springframework.bootspring-boot-starter-actuator

还需配置才能暴露端点(默认不暴露):

management:endpoints:web:exposure:include: '*'

连接Sentinel控制台的地址信息配置

spinrg:cloud:sentinel:transport:dashboard: localhost:8080

如针对接口限流:

@RestController@requestMapping("/pilot")public class PilotController {@SentinelResource(value = "pilot_list", blockHandler = "blockHandler")@GetMapping("/getList")public ResultBody list {Map> pilotServiceList = pilotService.getList;return ResultBody.success(pilotServiceList);}// 限流降级方法public ResultBody blockHandler(BlockException e) {log.warn("触发限流", e);return ResultBody.error("服务繁忙,请稍后再试");}}

value对应的资源名称:

@Configurationpublic class SentinelConfig implements BlockExceptionHandler {@PostConstructprivate void initFlowRules {List rules = new ArrayList;// 创建流控规则FlowRule rule = new FlowRule;// 设置受保护的资源rule.setResource("pilot_list");// 设置流控规则 QPSrule.setGrade(RuleConstant.FLOW_GRADE_QPS);// 设置受保护的资源阈值rule.setCount(1);rules.add(rule);// 加载规则FlowRuleManager.loadRules(rules);}@Beanpublic SentinelResourceAspect sentinelResourceAspect {return new SentinelResourceAspect;}@Overridepublic void handle(HttpServletRequest request, HttpServletResponse response, String resourceName, BlockException e) throws Exception {response.setStatus(429);response.getWriter.write("访问过于频繁,请稍后再试");}}

限流效果:

升级后,注意验证规则是否失效,避免版本差异bug。

https://github.com/alibaba/spring-cloud-alibaba/wiki/版本说明 魔都架构师 | 全网30W技术追随者 大厂分布式系统/数据中台实战专家 主导交易系统百万级流量调优 & 车联网平台架构 AIGC应用开发先行者 | 区块链落地实践者 以技术驱动创新,我们的征途是改变世界! 实战干货:编程严选网

来源:JavaEdge

相关推荐