Skip to content

HTTP 超时配置 (Http Timeouts Configuration)

HTTP 超时(响应超时和连接超时)可以为所有路由进行全局配置,也可以针对每个特定路由进行覆盖配置。

1. 全局超时 (Global Timeouts)

要配置全局 HTTP 超时:

  • connect-timeout 必须以毫秒为单位指定。
  • response-timeout 必须指定为 java.time.Duration 格式。

全局 HTTP 超时示例

yaml
spring:
  cloud:
    gateway:
      httpclient:
        connect-timeout: 1000
        response-timeout: 5s

2. 路由级超时 (Per-route Timeouts)

要配置每个路由的超时(Per-route timeouts):

  • connect-timeout 必须以毫秒为单位指定。
  • response-timeout 必须以毫秒为单位指定。

通过配置进行路由级超时设置

yaml
      - id: per_route_timeouts
        uri: https://example.org
        predicates:
          - name: Path
            args:
              pattern: /delay/{timeout}
        metadata:
          response-timeout: 200
          connect-timeout: 200

使用 Java DSL 进行路由级超时配置

java
import static org.springframework.cloud.gateway.support.RouteMetadataUtils.CONNECT_TIMEOUT_ATTR;
import static org.springframework.cloud.gateway.support.RouteMetadataUtils.RESPONSE_TIMEOUT_ATTR;

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder routeBuilder){
    return routeBuilder.routes()
            .route("test1", r -> {
                return r.host("*.somehost.org").and().path("/somepath")
                    .filters(f -> f.addRequestHeader("header1", "header-value-1"))
                    .uri("http://someuri")
                    .metadata(RESPONSE_TIMEOUT_ATTR, 200)
                    .metadata(CONNECT_TIMEOUT_ATTR, 200);
            })
            .build();
}

禁用超时

如果将路由级的 response-timeout 设置为负值,将禁用全局的 response-timeout 设置(即不超时)。

yaml
      - id: per_route_timeouts
        uri: https://example.org
        predicates:
          - name: Path
            args:
              pattern: /delay/{timeout}
        metadata:
          response-timeout: -1

补充教学 —— 两种超时分别指什么?

很多同学分不清 connect-timeoutresponse-timeout 的区别,导致生产环境配置错误。

  1. connect-timeout (连接超时)

    • 定义:指网关与下游服务建立 TCP 连接所花费的时间。
    • 场景:如果目标服务挂了、网络不通、或者防火墙拦截,通常会在几毫秒到几秒内抛出“连接超时”。
    • 建议值:通常设置得较短,如 1000ms3000ms。内网环境可以更短。
  2. response-timeout (响应超时)

    • 定义:指连接建立后,从发送请求到接收到完整响应的时间。
    • 场景:如果目标服务处理业务逻辑太慢(比如查数据库慢查询、死锁),或者网络传输很慢,会触发“响应超时”。
    • 建议值:根据业务容忍度设置。
      • 普通 API:3s - 5s
      • 复杂报表/文件下载:30s - 60s 或更长。
    • 注意:这个值不仅包含对方处理的时间,还包含数据回传的时间。如果是下载大文件,必须设大一点,否则传了一半虽然连接没断,但只要超过这个时间没传完,Netty 可能会切断连接。

优先级metadata 中的配置(路由级) > spring.cloud.gateway.httpclient 中的配置(全局)。

Based on Spring Framework.