在Java中,跨域(Cross-Origin)指的是在浏览器中,当一个网页(或者一个Web应用)从一个域名(或者端口、协议)发送请求到另一个域名(或者端口、协议)时,如果目标域名与源域名不同,就会发生跨域请求。
spring:
cloud:
gateway:
# default-filters:
# - DedupeResponseHeader=Access-Control-Allow-Origin
globalcors:
corsConfigurations:
'[/**]':
allowedOriginPatterns: "*" #允许全部访问源注意这个设置只对 spring boot 2.4+ 有效,低版本 使用 allowedOrigins: "*" 属性
allowed-methods: "*" #允许所有访问方式
allowed-headers: "*" #放行全部原始头信息
allow-credentials: true #允许跨域发送cookie
exposedHeaders: "Content-Disposition,Content-Type,Cache-Control" #剔除响应头中重复的值
2.路由转发:
spring:
cloud:
gateway:
routes:
#UPMS 模块
- id: pig-upms # 唯一的服务ID自定义
uri: lb://pig-upms # 注册中心的服务名称,实现负载均衡
predicates:
- Path=/admin/** #所有业务的请求前缀,会在② 中自动去除
- id: product #自定义(保证唯一)
uri: lb://gulimall-product(lb 表示负载均衡 gulimall-product表示服务名)
predicates: # 匹配条件
- Path=/api/product/**
filters:
- RewritePath=/api/product/(?<segment>.*),/$\{segment} #对发送到gateway的路径进行重写
#例如:
#访问gateway的是/api/product/list 那么重写后是:/list
#重写后的路径是真正访问的服务对应的接口。
3.限流
spring:
cloud:
gateway:
routes:
- id: requestratelimiter_route
uri: lb://pig-upms
order: 10000
predicates:
- Path=/admin/**
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 1 # 令牌桶每秒填充平均速率
redis-rate-limiter.burstCapacity: 3 # 令牌桶总容量
key-resolver: "#{@remoteAddrKeyResolver}" #SPEL表达式去的对应的bean
- StripPrefix=1
网关超时配置
路由超时配置可以为所有路由配置Http超时(响应和连接),并为每个特定路由覆盖Http超时。
- connect-timeout 必须以毫秒为单位指定连接超时时间.
- response-timeout 必须指定为java.time.Duration
spring:
cloud:
gateway:
httpclient:
connect-timeout: 1000
response-timeout: 10s