Spring Cloud Gateway 超时、CORS配置 | Spring Cloud 17
创始人
2024-06-01 12:08:53

一、Http超时配置

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

1.1 全局超时

配置全局 http 超时:

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

使用示例:

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

1.2 单路由超时

配置单路由超时:

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

使用示例:

spring:cloud:gateway:routes:- id: per_route_timeoutsuri: https://example.orgpredicates:- name: Pathargs:pattern: /delay/**filters:- StripPrefix=1metadata:response-timeout: 200connect-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_timeoutsuri: https://example.orgpredicates:- name: Pathargs:pattern: /delay/**filters:- StripPrefix=1metadata: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 # 是否允许携带cookiemaxAge: 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_routeuri: https://example.orgpredicates:- Path=/service/**metadata:corsallowedOrigins: '*'allowedMethods:- GET- POST- DELETE- PUTallowedHeaders: '*'maxAge: 360000 

上一篇:二十一、PG管理

下一篇:java -- stream流

相关内容

热门资讯

广东最新工伤保险缴费基数 北京...   根据广东省工伤保险相关政策规定,工伤保险缴费基数为单位职工共工资总额,具体的用人单位缴费总额还需...
贯彻广东省工伤保险条例维护广大...   为全面深入宣传社会保险法和《工伤保险条例》,提高工伤保险法律法规政策的社会知晓度,增强广大劳动者...
最新或2023(历届)“老工伤...   近日发布的最新或2023(历届)度人力资源和社会保障事业发展统计公报显示,最新或2023(历届)...
讲述工伤的典型案例 保障职工合...   在广东省开展工伤保险现场咨询宣传活动之际,番禺区人社局相关负责人为市民讲述工伤的典型案例   夫...
员工出差期间受伤算不算是工伤 ...   出差期间受伤到底算不算工伤保险呢?“我在陕西出差十多天时间,突然在宾馆感觉腿部疼痛,后经医院诊断...