流量治理不是限流那么简单:I/O 密集型 Java 服务的 6 层防线

流量治理不是限流那么简单:I/O 密集型 Java 服务的 6 层防线

一句话结论:限流只决定"让多少请求进来",真正决定系统能不能活下来的,是超时、隔离、熔断、重试预算和背压的组合。

版本基线:Spring Boot 3.x + Resilience4j 2.x;网关示例可用 Spring Cloud Gateway / Nginx。


1. 一次"扩容也救不了"的雪崩

大促 0 点,某订单服务 QPS 从 3,000 涨到 9,000。

  • 网关超时 3s,失败后重试 2 次;
  • Feign 客户端默认也重试;
  • 服务内部又对下游 RPC 重试 2 次;
  • DB 慢查询从 20ms 涨到 300ms;
  • Hikari 连接池 50,pending 很快到 200;
  • Tomcat 200 线程全部阻塞在"拿连接";
  • 网关看到 504,继续重试;
  • 最终下游实际收到的流量接近 9,000 × 3 × 3 = 81,000 QPS。

这不是流量太大,而是流量治理缺失:入口没有闸门,失败没有快速收敛,重试没有预算,慢依赖没有隔离。


2. 六层防线:从边缘到依赖

#mermaid-svg-XsstX0zvDpcZ7Vlt{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-XsstX0zvDpcZ7Vlt .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-XsstX0zvDpcZ7Vlt .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-XsstX0zvDpcZ7Vlt .error-icon{fill:#552222;}#mermaid-svg-XsstX0zvDpcZ7Vlt .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-XsstX0zvDpcZ7Vlt .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-XsstX0zvDpcZ7Vlt .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-XsstX0zvDpcZ7Vlt .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-XsstX0zvDpcZ7Vlt .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-XsstX0zvDpcZ7Vlt .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-XsstX0zvDpcZ7Vlt .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-XsstX0zvDpcZ7Vlt .marker{fill:#333333;stroke:#333333;}#mermaid-svg-XsstX0zvDpcZ7Vlt .marker.cross{stroke:#333333;}#mermaid-svg-XsstX0zvDpcZ7Vlt svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-XsstX0zvDpcZ7Vlt p{margin:0;}#mermaid-svg-XsstX0zvDpcZ7Vlt .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-XsstX0zvDpcZ7Vlt .cluster-label text{fill:#333;}#mermaid-svg-XsstX0zvDpcZ7Vlt .cluster-label span{color:#333;}#mermaid-svg-XsstX0zvDpcZ7Vlt .cluster-label span p{background-color:transparent;}#mermaid-svg-XsstX0zvDpcZ7Vlt .label text,#mermaid-svg-XsstX0zvDpcZ7Vlt span{fill:#333;color:#333;}#mermaid-svg-XsstX0zvDpcZ7Vlt .node rect,#mermaid-svg-XsstX0zvDpcZ7Vlt .node circle,#mermaid-svg-XsstX0zvDpcZ7Vlt .node ellipse,#mermaid-svg-XsstX0zvDpcZ7Vlt .node polygon,#mermaid-svg-XsstX0zvDpcZ7Vlt .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-XsstX0zvDpcZ7Vlt .rough-node .label text,#mermaid-svg-XsstX0zvDpcZ7Vlt .node .label text,#mermaid-svg-XsstX0zvDpcZ7Vlt .image-shape .label,#mermaid-svg-XsstX0zvDpcZ7Vlt .icon-shape .label{text-anchor:middle;}#mermaid-svg-XsstX0zvDpcZ7Vlt .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-XsstX0zvDpcZ7Vlt .rough-node .label,#mermaid-svg-XsstX0zvDpcZ7Vlt .node .label,#mermaid-svg-XsstX0zvDpcZ7Vlt .image-shape .label,#mermaid-svg-XsstX0zvDpcZ7Vlt .icon-shape .label{text-align:center;}#mermaid-svg-XsstX0zvDpcZ7Vlt .node.clickable{cursor:pointer;}#mermaid-svg-XsstX0zvDpcZ7Vlt .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-XsstX0zvDpcZ7Vlt .arrowheadPath{fill:#333333;}#mermaid-svg-XsstX0zvDpcZ7Vlt .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-XsstX0zvDpcZ7Vlt .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-XsstX0zvDpcZ7Vlt .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-XsstX0zvDpcZ7Vlt .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-XsstX0zvDpcZ7Vlt .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-XsstX0zvDpcZ7Vlt .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-XsstX0zvDpcZ7Vlt .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-XsstX0zvDpcZ7Vlt .cluster text{fill:#333;}#mermaid-svg-XsstX0zvDpcZ7Vlt .cluster span{color:#333;}#mermaid-svg-XsstX0zvDpcZ7Vlt div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-XsstX0zvDpcZ7Vlt .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-XsstX0zvDpcZ7Vlt rect.text{fill:none;stroke-width:0;}#mermaid-svg-XsstX0zvDpcZ7Vlt .icon-shape,#mermaid-svg-XsstX0zvDpcZ7Vlt .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-XsstX0zvDpcZ7Vlt .icon-shape p,#mermaid-svg-XsstX0zvDpcZ7Vlt .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-XsstX0zvDpcZ7Vlt .icon-shape rect,#mermaid-svg-XsstX0zvDpcZ7Vlt .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-XsstX0zvDpcZ7Vlt .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-XsstX0zvDpcZ7Vlt .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-XsstX0zvDpcZ7Vlt :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 客户端
① CDN / WAF

黑名单 · 防刷 · 静态缓存
② Nginx / SLB

连接数 · 漏桶限流 · 超时
③ API Gateway

路由级 QPS · 鉴权 · 熔断
④ 服务层

并发隔离 Bulkhead · 降级
⑤ 依赖层

RPC/DB/Redis 超时 · 熔断
⑥ 客户端/消费端

重试预算 · 背压 · 幂等

层 主要职责 典型手段 不该做什么
① 边缘 挡住明显恶意/无效流量 WAF、IP/设备限速、静态缓存 把业务限流全放这里
② LB/Nginx 连接级保护、粗粒度限流 limit_conn、limit_req、超时 用单机限流冒充全局
③ 网关 全局 QPS、鉴权、路由、熔断 Token Bucket、路由级配额、JWT 每个请求都访问 Redis 做限流
④ 服务 按依赖隔离、降级 Semaphore/线程池隔离、舱壁 所有依赖共用一个线程池
⑤ 依赖 快速失败、熔断、恢复 连接/读超时、CircuitBreaker 超时设置比上游还长
⑥ 客户端 重试预算、幂等、背压 退避 + 抖动、Retry Budget 多层无脑重试

核心原则:越靠近入口,越做"总量控制";越靠近依赖,越做"并发控制"。


3. 限流算法:别只会固定窗口

算法 优点 缺点 适用
固定窗口 实现简单 临界点双倍流量 粗粒度、低精度
滑动窗口 平滑、精度高 需要存储/计算 网关、Redis
漏桶 恒定输出,天然削峰 突发流量被排队 保护下游、队列
令牌桶 允许一定突发 参数需要调 API 限流常用
并发限制 直接保护资源 不控制 QPS I/O 密集型首选补充

3.1 单机 + 分布式两级限流

高 QPS 下,每个请求都去 Redis 取令牌,会把限流器本身变成瓶颈。更实用的结构是:

text 复制代码
本地令牌桶(快) + 全局配额租约(准)
  • 每个实例按 全局阈值 / 实例数 预取一批令牌(例如每次 100 个);
  • 本地令牌用完,再去 Redis 申请下一批;
  • 允许少量误差,换取数量级的性能提升;
  • 对强一致配额(如付费 API)再单独走 Redis Lua。
lua 复制代码
-- 滑动窗口限流(简化版):key 为限流维度,window 为窗口毫秒,limit 为阈值
-- KEYS[1] = rate:{key}
-- ARGV[1] = now_ms, ARGV[2] = window_ms, ARGV[3] = limit
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, now - window)
local count = redis.call('ZCARD', KEYS[1])
if count >= limit then
  return 0
end
redis.call('ZADD', KEYS[1], now, now .. ':' .. math.random())
redis.call('PEXPIRE', KEYS[1], window)
return 1

生产建议:优先用成熟组件(Sentinel、Gateway RequestRateLimiter、Envoy),不要自己造分布式限流。Lua 脚本要处理时钟、key 过期、热点 key 和 Redis 故障降级。

3.2 QPS 限流不够:并发限流更贴近 I/O 本质

同样 1,000 QPS,如果每次请求耗时 10ms,需要 10 个并发;如果耗时 1s,需要 1,000 个并发。QPS 相同,资源压力完全不同。

因此对 DB、Redis、下游 RPC,应该优先做并发限制:

java 复制代码
Semaphore dbGate = new Semaphore(32);

public Order query(Long id) throws InterruptedException {
    if (!dbGate.tryAcquire(50, TimeUnit.MILLISECONDS)) {
        throw new RejectedExecutionException("db concurrency exceeded");
    }
    try {
        return orderRepository.findById(id).orElseThrow();
    } finally {
        dbGate.release();
    }
}

参数怎么定?

text 复制代码
并发上限 ≈ 下游可承受并发 × 安全系数(0.7~0.8)

如果 DB 实测在 64 并发时 P99 开始明显上升,应用侧总闸门就设 40~50,再按实例数分摊。不要用应用实例数 × 每实例线程数去倒推 DB 容量。


4. 超时:一条预算,不是一堆数字

4.1 超时预算表

环节 超时 说明
客户端连接 1s 建连失败快速重试(仅幂等)
网关路由 800ms 必须小于客户端总超时
服务读请求体 200ms 防止慢客户端
DB 查询 150ms 慢 SQL 单独治理
Redis 20ms 含网络,禁止无限重试
下游 RPC 300ms 含连接池获取
服务总处理 700ms 给网关留余量
客户端总超时 1s 最终 SLO

4.2 超时传递

http 复制代码
X-Request-Deadline: 1730000000123

服务收到后计算 remaining = deadline - now,每次调用下游前检查:

java 复制代码
long remaining = deadline - System.currentTimeMillis();
if (remaining < 50) {
    throw new DeadlineExceededException();
}
client.call(request, Math.min(remaining, 300));

没有 deadline 传递,就会出现"上游已经放弃,下游还在拼命算"的无效工作。


5. 重试:只在一层,带预算

5.1 重试三原则

  1. 幂等:GET/查询可以重试;下单/支付必须有幂等键。
  2. 一层:网关、RPC 客户端、服务内部,只选一层。
  3. 预算:重试流量不超过正常流量的 10%,否则直接失败。

5.2 指数退避 + 抖动

java 复制代码
long base = 50; // ms
long cap = 1000;
long sleep = Math.min(cap, base * (1L << attempt));
sleep = ThreadLocalRandom.current().nextLong(sleep / 2, sleep + 1);
Thread.sleep(sleep);

没有抖动的重试会让所有客户端在同一时刻再次冲击下游,形成"重试风暴"。

5.3 Resilience4j 配置

java 复制代码
RetryConfig retry = RetryConfig.custom()
    .maxAttempts(2)                       // 首次 + 1 次重试
    .waitDuration(Duration.ofMillis(100))
    .retryExceptions(IOException.class, TimeoutException.class)
    .ignoreExceptions(BusinessException.class)
    .build();

CircuitBreakerConfig cb = CircuitBreakerConfig.custom()
    .failureRateThreshold(50)
    .slowCallRateThreshold(50)
    .slowCallDurationThreshold(Duration.ofMillis(300))
    .minimumNumberOfCalls(20)
    .slidingWindowSize(50)
    .waitDurationInOpenState(Duration.ofSeconds(10))
    .permittedNumberOfCallsInHalfOpenState(5)
    .build();

BulkheadConfig bulkhead = BulkheadConfig.custom()
    .maxConcurrentCalls(32)
    .maxWaitDuration(Duration.ofMillis(50))
    .build();

组合顺序很重要。Resilience4j 常见的推荐顺序(从外到内)是:

text 复制代码
Retry → CircuitBreaker → RateLimiter → TimeLimiter → Bulkhead → 业务
  • Retry 在最外层:每次重试都重新经过熔断器和舱壁;退避期间不占舱壁许可。
  • Bulkhead 在最内层:只保护真正调用下游的那一小段,不把重试等待也算进并发许可。
  • 如果把 Retry 放进 Bulkhead 内,重试的退避时间也会占着许可,容易把舱壁打满。
  • 顺序不是教条:如果你希望熔断器按"一次逻辑调用"而不是"每次重试"统计失败率,可以把 CB 放在 Retry 外层,但要同步调整指标口径。

6. 熔断与降级:给下游恢复窗口

6.1 熔断状态机

#mermaid-svg-kyaER6jK9WxdvZ9h{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-kyaER6jK9WxdvZ9h .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-kyaER6jK9WxdvZ9h .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-kyaER6jK9WxdvZ9h .error-icon{fill:#552222;}#mermaid-svg-kyaER6jK9WxdvZ9h .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-kyaER6jK9WxdvZ9h .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-kyaER6jK9WxdvZ9h .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-kyaER6jK9WxdvZ9h .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-kyaER6jK9WxdvZ9h .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-kyaER6jK9WxdvZ9h .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-kyaER6jK9WxdvZ9h .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-kyaER6jK9WxdvZ9h .marker{fill:#333333;stroke:#333333;}#mermaid-svg-kyaER6jK9WxdvZ9h .marker.cross{stroke:#333333;}#mermaid-svg-kyaER6jK9WxdvZ9h svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-kyaER6jK9WxdvZ9h p{margin:0;}#mermaid-svg-kyaER6jK9WxdvZ9h defs #statediagram-barbEnd{fill:#333333;stroke:#333333;}#mermaid-svg-kyaER6jK9WxdvZ9h g.stateGroup text{fill:#9370DB;stroke:none;font-size:10px;}#mermaid-svg-kyaER6jK9WxdvZ9h g.stateGroup text{fill:#333;stroke:none;font-size:10px;}#mermaid-svg-kyaER6jK9WxdvZ9h g.stateGroup .state-title{font-weight:bolder;fill:#131300;}#mermaid-svg-kyaER6jK9WxdvZ9h g.stateGroup rect{fill:#ECECFF;stroke:#9370DB;}#mermaid-svg-kyaER6jK9WxdvZ9h g.stateGroup line{stroke:#333333;stroke-width:1;}#mermaid-svg-kyaER6jK9WxdvZ9h .transition{stroke:#333333;stroke-width:1;fill:none;}#mermaid-svg-kyaER6jK9WxdvZ9h .stateGroup .composit{fill:white;border-bottom:1px;}#mermaid-svg-kyaER6jK9WxdvZ9h .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px;}#mermaid-svg-kyaER6jK9WxdvZ9h .state-note{stroke:#aaaa33;fill:#fff5ad;}#mermaid-svg-kyaER6jK9WxdvZ9h .state-note text{fill:black;stroke:none;font-size:10px;}#mermaid-svg-kyaER6jK9WxdvZ9h .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5;}#mermaid-svg-kyaER6jK9WxdvZ9h .edgeLabel .label rect{fill:#ECECFF;opacity:0.5;}#mermaid-svg-kyaER6jK9WxdvZ9h .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-kyaER6jK9WxdvZ9h .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-kyaER6jK9WxdvZ9h .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-kyaER6jK9WxdvZ9h .edgeLabel .label text{fill:#333;}#mermaid-svg-kyaER6jK9WxdvZ9h .label div .edgeLabel{color:#333;}#mermaid-svg-kyaER6jK9WxdvZ9h .stateLabel text{fill:#131300;font-size:10px;font-weight:bold;}#mermaid-svg-kyaER6jK9WxdvZ9h .node circle.state-start{fill:#333333;stroke:#333333;}#mermaid-svg-kyaER6jK9WxdvZ9h .node .fork-join{fill:#333333;stroke:#333333;}#mermaid-svg-kyaER6jK9WxdvZ9h .node circle.state-end{fill:#9370DB;stroke:white;stroke-width:1.5;}#mermaid-svg-kyaER6jK9WxdvZ9h .end-state-inner{fill:white;stroke-width:1.5;}#mermaid-svg-kyaER6jK9WxdvZ9h .node rect{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-kyaER6jK9WxdvZ9h .node polygon{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-kyaER6jK9WxdvZ9h #statediagram-barbEnd{fill:#333333;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-cluster rect{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-kyaER6jK9WxdvZ9h .cluster-label,#mermaid-svg-kyaER6jK9WxdvZ9h .nodeLabel{color:#131300;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-cluster rect.outer{rx:5px;ry:5px;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-state .divider{stroke:#9370DB;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-state .title-state{rx:5px;ry:5px;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-cluster.statediagram-cluster .inner{fill:white;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-cluster.statediagram-cluster-alt .inner{fill:#f0f0f0;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-cluster .inner{rx:0;ry:0;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-state rect.basic{rx:5px;ry:5px;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#f0f0f0;}#mermaid-svg-kyaER6jK9WxdvZ9h .note-edge{stroke-dasharray:5;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-note rect{fill:#fff5ad;stroke:#aaaa33;stroke-width:1px;rx:0;ry:0;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-note rect{fill:#fff5ad;stroke:#aaaa33;stroke-width:1px;rx:0;ry:0;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-note text{fill:black;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram-note .nodeLabel{color:black;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagram .edgeLabel{color:red;}#mermaid-svg-kyaER6jK9WxdvZ9h #dependencyStart,#mermaid-svg-kyaER6jK9WxdvZ9h #dependencyEnd{fill:#333333;stroke:#333333;stroke-width:1;}#mermaid-svg-kyaER6jK9WxdvZ9h .statediagramTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-kyaER6jK9WxdvZ9h :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 失败率/慢调用率超阈值
等待窗口结束
试探成功
试探失败
CLOSED
OPEN
HALF_OPEN

6.2 降级策略

场景 降级动作 注意
推荐服务超时 返回热门兜底 不要返回空列表伤体验
积分/等级超时 返回默认值 + 异步补 不要阻塞主链路
非核心字段超时 字段置空/省略 前端要能处理
DB 只读副本延迟 强制走主库(少量) 防止主库被打爆
缓存故障 本地缓存 + 限流回源 不要全量穿透 DB

降级不是"返回 null",而是有产品语义的兜底。


7. 请求链路时序

下游 Bulkhead 服务 Gateway Nginx 客户端 下游 Bulkhead 服务 Gateway Nginx 客户端 #mermaid-svg-UbyiLvVe8AO7Uc3P{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-UbyiLvVe8AO7Uc3P .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-UbyiLvVe8AO7Uc3P .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-UbyiLvVe8AO7Uc3P .error-icon{fill:#552222;}#mermaid-svg-UbyiLvVe8AO7Uc3P .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-UbyiLvVe8AO7Uc3P .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-UbyiLvVe8AO7Uc3P .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-UbyiLvVe8AO7Uc3P .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-UbyiLvVe8AO7Uc3P .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-UbyiLvVe8AO7Uc3P .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-UbyiLvVe8AO7Uc3P .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-UbyiLvVe8AO7Uc3P .marker{fill:#333333;stroke:#333333;}#mermaid-svg-UbyiLvVe8AO7Uc3P .marker.cross{stroke:#333333;}#mermaid-svg-UbyiLvVe8AO7Uc3P svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-UbyiLvVe8AO7Uc3P p{margin:0;}#mermaid-svg-UbyiLvVe8AO7Uc3P .actor{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-UbyiLvVe8AO7Uc3P text.actor>tspan{fill:black;stroke:none;}#mermaid-svg-UbyiLvVe8AO7Uc3P .actor-line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);}#mermaid-svg-UbyiLvVe8AO7Uc3P .innerArc{stroke-width:1.5;stroke-dasharray:none;}#mermaid-svg-UbyiLvVe8AO7Uc3P .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333;}#mermaid-svg-UbyiLvVe8AO7Uc3P .messageLine1{stroke-width:1.5;stroke-dasharray:2,2;stroke:#333;}#mermaid-svg-UbyiLvVe8AO7Uc3P #arrowhead path{fill:#333;stroke:#333;}#mermaid-svg-UbyiLvVe8AO7Uc3P .sequenceNumber{fill:white;}#mermaid-svg-UbyiLvVe8AO7Uc3P #sequencenumber{fill:#333;}#mermaid-svg-UbyiLvVe8AO7Uc3P #crosshead path{fill:#333;stroke:#333;}#mermaid-svg-UbyiLvVe8AO7Uc3P .messageText{fill:#333;stroke:none;}#mermaid-svg-UbyiLvVe8AO7Uc3P .labelBox{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-UbyiLvVe8AO7Uc3P .labelText,#mermaid-svg-UbyiLvVe8AO7Uc3P .labelText>tspan{fill:black;stroke:none;}#mermaid-svg-UbyiLvVe8AO7Uc3P .loopText,#mermaid-svg-UbyiLvVe8AO7Uc3P .loopText>tspan{fill:black;stroke:none;}#mermaid-svg-UbyiLvVe8AO7Uc3P .loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);}#mermaid-svg-UbyiLvVe8AO7Uc3P .note{stroke:#aaaa33;fill:#fff5ad;}#mermaid-svg-UbyiLvVe8AO7Uc3P .noteText,#mermaid-svg-UbyiLvVe8AO7Uc3P .noteText>tspan{fill:black;stroke:none;}#mermaid-svg-UbyiLvVe8AO7Uc3P .activation0{fill:#f4f4f4;stroke:#666;}#mermaid-svg-UbyiLvVe8AO7Uc3P .activation1{fill:#f4f4f4;stroke:#666;}#mermaid-svg-UbyiLvVe8AO7Uc3P .activation2{fill:#f4f4f4;stroke:#666;}#mermaid-svg-UbyiLvVe8AO7Uc3P .actorPopupMenu{position:absolute;}#mermaid-svg-UbyiLvVe8AO7Uc3P .actorPopupMenuPanel{position:absolute;fill:#ECECFF;box-shadow:0px 8px 16px 0px rgba(0,0,0,0.2);filter:drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));}#mermaid-svg-UbyiLvVe8AO7Uc3P .actor-man line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-UbyiLvVe8AO7Uc3P .actor-man circle,#mermaid-svg-UbyiLvVe8AO7Uc3P line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;stroke-width:2px;}#mermaid-svg-UbyiLvVe8AO7Uc3P :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} alt 成功 超时/失败 alt 许可不足 获得许可 请求 1 limit_conn / limit_req 2 转发 3 全局 QPS / 鉴权 / deadline 4 转发(剩余预算) 5 tryAcquire(50ms) 6 拒绝 7 503 + Retry-After 8 调用(超时 = min(剩余预算, 300ms)) 9 结果 10 200 11 Timeout 12 熔断器记录 13 降级/503 14 响应 15


8. Nginx 粗粒度保护

nginx 复制代码
http {
  limit_req_zone $binary_remote_addr zone=api:10m rate=20r/s;
  limit_conn_zone $binary_remote_addr zone=conn:10m;

  upstream order_service {
    server 10.0.0.11:8080 max_fails=3 fail_timeout=10s;
    server 10.0.0.12:8080 max_fails=3 fail_timeout=10s;
    keepalive 64;
  }

  server {
    location /api/order/ {
      limit_req zone=api burst=40 nodelay;
      limit_conn conn 20;
      proxy_connect_timeout 1s;
      proxy_read_timeout 2s;
      proxy_next_upstream error timeout http_502;
      proxy_next_upstream_tries 1;   # 只重试一次,避免放大
      proxy_pass http://order_service;
    }
  }
}

注意:proxy_next_upstream_tries 1 仍可能在多台上游间重试,务必确认接口幂等。


9. 指标与告警

指标 说明 告警建议
http_requests_total{status=429} 被限流 持续 > 1% 关注
bulkhead_rejected_total 并发舱壁拒绝 持续 > 0.5%
circuitbreaker_state 熔断状态 OPEN 立即告警
http_client_duration_p99 下游 P99 超预算 80%
retry_total / request_total 重试率 > 10%
gateway_queue_depth 排队深度 持续上升
db_pool_pending 等连接线程 > 0 持续 1 分钟

10. 常见误区

误区 后果 正确做法
三层都加重试 故障时流量翻倍 只在一层重试,设预算
限流只做单机 集群总量超 网关全局 + 本地租约
熔断器按实例看 全局已挂,单机还在放量 聚合监控,网关层熔断
超时上游短下游长 下游做无效功 deadline 传递
用平均 RT 设阈值 尾延迟被忽略 用 P99 + 慢调用比例
拒绝请求不带 Retry-After 客户端立刻重试 返回 429/503 + 退避提示
降级返回 null 前端 NPE 有语义的兜底对象

11. Checklist

text 复制代码
[ ] 每个入口有 QPS 或并发限制,阈值来自压测
[ ] 限流是全局 + 本地两级,不依赖单机
[ ] 每个强依赖有独立 Bulkhead
[ ] 所有外部调用有连接/读取/总超时
[ ] deadline 从入口传递到最下游
[ ] 重试只在一层、幂等、退避 + 抖动 + 预算
[ ] 熔断器覆盖慢调用,不只覆盖异常
[ ] 降级有产品语义,前端可处理
[ ] 429/503 返回 Retry-After
[ ] 限流/熔断/重试指标有看板与告警

上一篇 :01 · 总纲

下一篇 :03 · 线程模型:虚拟线程与并发度

相关推荐
学长毕设22 分钟前
基于SpringBoot智慧养老服务平台设计与实现-附源码
java·spring boot·后端
曹牧1 小时前
Java:“刷新雪崩”
java·开发语言
秋天的怀念_David1 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
Forget the Dream3 小时前
Spring AI 2.0 系列(二):第一个 ChatClient——从注入到一次完整调用
java·人工智能·spring boot·ai·springai
黑十4 小时前
FDE 怎么快速搭一个可演示页面?最小前端方案
java·大数据·前端·数据库·人工智能
神明不懂浪漫4 小时前
【第八章】多线程(一)
java·开发语言·经验分享·笔记
用户54817845909505 小时前
Java 与 Python 在大模型与智能体领域的选型
java·python
文丑颜不良啊5 小时前
LeetCode3341~3360题目解析
java·leetcode
hai_android5 小时前
一行 asLiveData,背后是一座生命周期的桥
android·java·kotlin