一、Http超时配置
Spring Cloud Gateway 可以为所有路由配置 Http 超时(响应和连接),并为每个特定路由覆盖设置。
1.1 全局超时
配置全局 http 超时:
connect-timeout必须以毫秒为单位指定。response-timeout必须指定为java.time.Duration
使用示例:
spring:
cloud:
gateway:
httpclient:
connect-timeout: 1000
response-timeout: 5s
1.2 单路由超时
配置单路由超时:
connect-timeout必须以毫秒为单位指定。response-timeout必须以毫秒为单位指定。
使用示例:
spring:
cloud:
gateway:
routes:
- id: per_route_timeouts
uri: https://example.org
predicates:
- name: Path
args:
pattern: /delay/**
filters:
- StripPrefix=1
metadata:
response-timeout: 200
connect-timeout: 200
使用Java DSL 对单个路由超时配置:
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("per_route_timeouts", r -> {
return r.path("/delay/**")
.filters(f -> f.stripPrefix(1))
.uri("https://example.org")
.metadata(RESPONSE_TIMEOUT_ATTR, 200)
.metadata(CONNECT_TIMEOUT_ATTR, 200);
})
.build();
}
response-timeout具有负值的每个路由将禁用全局response-timeout值。
spring:
cloud:
gateway:
routes:
- id: per_route_timeouts
uri: https://example.org
predicates:
- name: Path
args:
pattern: /delay/**
filters:
- StripPrefix=1
metadata:
response-timeout: -1
1.3 超时效果

二、CORS配置
Spring Cloud Gateway可以为网关配置全局或单路由的跨域行为控制。两者都提供相同的特性。
2.1 全局 CORS 配置
全局CORS配置:是 URL 模式到Spring FrameworkCorsConfiguration的映射。
spring:
cloud:
gateway:
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
cors-configurations:
'[/**]':
allowedOrigins: "https://docs.spring.io" # 允许哪些网站的跨域请求
allowedMethods: # 允许的跨域的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期
此示例中,允许来自docs.spring.io所有 GET 请求方式的CORS请求。
spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping属性设置为true:支持 CORS 预检请求。
options请求就是预检请求,可用于检测服务器允许的http方法。当发起跨域请求时,由于安全原因,触发一定条件时,浏览器会在正式请求之前自动先发起OPTIONS请求,即CORS预检请求,服务器若接受该跨域请求,浏览器才继续发起正式请求。
2.2 路由 CORS 配置
路由配置允许将 CORS 作为带有 key 的元数据直接应用于路由CORS。与全局配置的情况一样,属性属于Spring FrameworkCorsConfiguration。
spring:
cloud:
gateway:
routes:
- id: cors_route
uri: https://example.org
predicates:
- Path=/service/**
metadata:
cors
allowedOrigins: '*'
allowedMethods:
- GET
- POST
- DELETE
- PUT
allowedHeaders: '*'
maxAge: 360000
![[qiankun+nuxt]子应用请求本地文件报错404](https://img-blog.csdnimg.cn/3b92afcf06a84e25ad8c6e75e2f9d452.png)

















