图片预览

滚轮缩放 · 拖动移动 · Esc 关闭

Skip to content

Sentinel 限流熔断 ​

当前实现内容可在当前源码中定位并复现
适用范围
muotai-common-sentinel 的接入与维护
阅读对象
后端开发、测试和运维
源码基线
muotai-backend 提交 a08dae999(muotai-common 5.8.0)
源文件
muotai-backend/muotai-common/muotai-common-sentinel/
核对日期
2026-11-28

作用与提供的能力 ​

muotai-common-sentinel 封装 Sentinel(1.8.4)在墨台微服务中的标准接入:统一 Servlet 侧请求来源解析、限流/熔断阻断 JSON 响应以及 OpenFeign 侧的 Sentinel 降级构建器,避免业务服务重复编写样板适配代码。

接入与使用 ​

在业务模块的 pom.xml 中加入 com.aroundix:muotai-common-sentinel(同仓库子模块沿用父 POM 版本):

  1. 配置服务的 Sentinel 控制台地址或 Nacos 规则数据源,按实际容量规划流控、熔断或热点规则。
  2. MuotaiSentinelAutoConfiguration 在 spring.cloud.openfeign.sentinel.enabled 未显式关闭时自动参与装配;显式设为 true 开启 Feign 侧熔断降级适配。
  3. 为关键 Feign 客户端编写 fallback / fallbackFactory,定义降级后的业务兜底行为。

最小示例 ​

yaml
spring:
  cloud:
    openfeign:
      sentinel:
        enabled: true

限流响应与来源识别机制 ​

扩展组件源码位置当前行为与约定
MuotaiUrlBlockHandlersentinel/handle/Servlet 侧 BlockExceptionHandler:触发限流/熔断后固定返回 HTTP 429 (Too Many Requests),响应体为 R.failed(e.getMessage()) JSON
MuotaiHeaderRequestOriginParsersentinel/parser/从请求头 Allow 读取调用来源标识,供 Sentinel 授权/来源限流规则使用
MuotaiSentinelFeignsentinel/feign/扩展 Feign Builder 与调用处理器,将 Feign 接口资源接入 Sentinel 熔断与降级回调

客户端与代理协同注意

  1. 双层错误识别:触发限流时服务端同时返回 HTTP 429 与业务失败结构 R.failed(...),前端与上游服务需同时兼容 HTTP 状态码与业务码。
  2. 保护 Allow 来源头:若配置了基于调用来源的授权或限流规则,须确保边缘网关或代理层可信地覆写并保护 Allow 请求头,防止客户端伪造来源绕过规则。

配置与装配速查 ​

项目当前源码入口
装配方式MuotaiSentinelAutoConfiguration 自动配置
关键配置或参数spring.cloud.openfeign.sentinel.enabled
默认限流响应HTTP 429 + R.failed(e.getMessage())
外部前提Sentinel 控制台/规则数据源、业务流控规则与 Feign 降级实现

代码组织 ​

  • 根目录:MuotaiSentinelAutoConfiguration 装配 Feign Builder、Servlet 阻断处理器与来源解析器。
  • sentinel/parser/:MuotaiHeaderRequestOriginParser 解析请求来源。
  • sentinel/handle/:MuotaiUrlBlockHandler 处理阻断与业务异常响应。
  • sentinel/feign/:MuotaiSentinelFeign 适配 OpenFeign 熔断降级。

验证与排障 ​

在 muotai-backend 根目录运行编译校验:

bash
mvn -B -pl :muotai-common-sentinel -am test-compile -DskipTests

运行期验收步骤

  1. 在测试环境对单个接口配置低阈值 QPS 流控规则,压测确认超限时返回 HTTP 429 与预期 JSON 体。
  2. 对带降级实现的 Feign 接口触发异常或慢调用熔断,验证 fallback / fallbackFactory 正常执行。

使用边界

  • 本模块只提供接入适配机制,不自带通用流控阈值;所有阈值须结合业务压测结果在 Sentinel 规则源中维护。
  • 网关(WebFlux)与普通业务微服务(Servlet)的资源名和拦截链路不同,须分别核对规则配置。

源码入口:muotai-backend/muotai-common/muotai-common-sentinel/src/main/java/com/aroundix/muotai/common/sentinel/MuotaiSentinelAutoConfiguration.java。相关上下游见公共组件总览与Feign 服务调用。