Spring Cloud Gateway 开发随笔

Gateway 配置

路由超时时间配置

路由超时配置可以为所有路由配置 HTTP 超时(响应和连接),并为每个特定路由覆盖 HTTP 超时。

全局路由的超时时间配置

配置全局 HTTP 超时(响应和连接),需要使用以下两个参数:

  • connect-timeout:必须以毫秒为单位指定连接超时时间
  • response-timeout:必须指定为 java.time.Duration
1
2
3
4
5
6
spring:
cloud:
gateway:
httpclient:
connect-timeout: 1000
response-timeout: 5s

每个路由的超时时间配置

可以通过路由的 metadata 以下两个参数配置每个路由的超时时间:

  • connect-timeout:必须以毫秒为单位指定连接超时时间
  • response-timeout:必须以毫秒为单位指定响应超时时间
1
2
3
4
5
6
7
8
9
- id: per_route_timeouts
uri: https://example.org
predicates:
- name: Path
args:
pattern: /delay/{timeout}
metadata:
response-timeout: 1000
connect-timeout: 1000

使用 Java DSL 为每个路由配置超时时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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, 1000)
.metadata(CONNECT_TIMEOUT_ATTR, 1000);
})
.build();
}

Gateway 负载均衡

负载均衡失效,响应 503 错误码

  • 版本说明
Spring BootSpring CloudSpring Cloud Alibaba
2.6.32021.0.12021.0.1.0
  • Gateway 的配置
1
2
3
4
5
6
7
8
9
10
11
12
13
spring:
cloud:
nacos:
discovery:
server-addr: 192.168.56.103:8848
gateway:
routes:
- id: tmall-product
uri: lb://tmall-product
predicates:
- Path=/api/**
filters:
- RewritePath=/api(?<segment>/?.*), /tmall-product/$\{segment}
  • 问题描述

Gateway 使用 Nacos 作为配置中心,基于上述的配置内容,当通过 uri: http://127.0.0.1:9090 去直接调用 tmall-product 服务时,是可以正常调用的,但是使用 uri: lb://tmall-product 时就无法调用服务,Gateway 返回 503 错误码。

  • 解决方案

造成 Gateway 负载均衡失效的原因是,从 Spring Cloud 2020 版本开始,Spring Cloud 弃用了 Ribbon,使用 Spring Cloud Loadbalancer 作为客户端的负载均衡组件;因此 Spring Cloud Alibaba 在 2021 版本的 Nacos 中也移除了 Ribbon 的依赖,最终导致 Gateway 无法通过 lb:// 路由到指定的服务,继而出现了 503 错误码。解决方案是引入 Spring Cloud Loadbalancer 的 Maven 坐标即可:

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>