Spring Cloud Gateway response-timeout 和 connect-timeout
一、概念对比总览
在 Spring Cloud Gateway(或任何网络客户端)中,response-timeout和connect-timeout作用于网络请求的不同阶段。
| 配置项 | 作用阶段 | 含义说明 | 默认值(Spring Cloud Gateway) | 单位 |
|---|---|---|---|---|
connect-timeout |
连接建立阶段 | 客户端与目标服务建立 TCP 连接的最大等待时间 | 通常 45s 或 10s(版本相关) | 毫秒 / Duration |
response-timeout |
请求 - 响应阶段 | 从发送请求开始,到收到完整响应的最大等待时间 | 30s | Duration(如30s) |
简单记忆:
connect-timeout→ “连得上吗?”response-timeout→ “回得来吗?”
二、详细解释
1. connect-timeout(连接超时)
作用:
控制网关尝试与下游服务(如lb://user-service)建立 TCP 连接的最大等待时间。
触发场景:
- 下游服务宕机、未启动
- 网络不通、防火墙阻断
- DNS 解析失败或负载均衡找不到实例
- 服务注册中心无可用实例
超时后果:
- 抛出
Connection refused、UnknownHostException、TimeoutException等 - 网关返回 502 Bad Gateway 或 503 Service Unavailable
示例:
spring:
cloud:
gateway:
httpclient:
connect-timeout: 5000 # 5 秒内必须建立连接,否则失败
如果 5 秒内 TCP 握手没完成 → 超时失败。
2. response-timeout(响应超时)
作用:
控制从网关发送请求给下游服务开始,到接收完完整响应体为止的最大等待时间。
触发场景:
- 下游服务处理慢(如复杂计算、数据库慢查询、死锁)
- 下游服务卡住未返回(如线程阻塞、无限循环)
- 网络延迟高、带宽不足(大文件传输慢)
超时后果:
- 抛出
TimeoutException: Response took longer than timeout: PT30S - 网关主动断开连接,返回 504 Gateway Timeout
示例:
spring:
cloud:
gateway:
httpclient:
response-timeout: 60s # 允许下游服务最多 60 秒返回结果
如果下游服务 60 秒还没返回完整响应 → 网关断开,返回 504。
三、在 Spring Cloud Gateway 中的配置方式
spring:
cloud:
gateway:
httpclient:
connect-timeout: 10000 # 10 秒(单位:毫秒,老版本常用)
response-timeout: 60s # 60 秒(Duration 格式,推荐写法)
注意:
- 在旧版本(Greenwich 及以前),
response-timeout可能只支持毫秒数字,如60000- 在新版本(Hoxton / 2020+),推荐使用
60s、2m等 Duration 格式
针对特定路由:
- id: per_route_timeouts
uri: https://example.org
predicates:
- name: Path
args:
pattern: /delay/{timeout}
metadata:
response-timeout: 200
connect-timeout: 200
四、如何选择合适的超时值?
| 场景 | connect-timeout 建议 | response-timeout 建议 |
|---|---|---|
| 普通 API(CRUD) | 2s ~ 5s | 10s ~ 30s |
| 文件上传/下载 | 5s ~ 10s | 60s ~ 300s(根据文件大小) |
| 报表生成、大数据导出 | 5s | 300s+(5 分钟以上) |
| 内部高速服务调用 | 1s | 5s |
| 外部第三方 API | 10s | 30s ~ 60s |
原则:
connect-timeout尽量短(快速失败,避免线程阻塞)response-timeout根据业务实际耗时设置(可路由级别单独配置)
浙公网安备 33010602011771号