SpringCloud Gateway使用和配置,
SpringCloud Gateway routes详细配置,SpringCloud Gateway predicates详细配置SpringCloud Gateway 跨域配置,SpringCloud Gateway 超时配置
================================
©Copyright 蕃薯耀 2021-03-18
https://www.cnblogs.com/fanshuyao/
一、SpringCloud Gateway概述
spring cloud gateway旨在提供一种简单而有效的方法来路由到api,并为它们提供跨领域的关注点,例如:安全性、监视/度量和恢复能力。
客户端向Spring云网关发出请求。如果网关处理程序映射确定请求与路由匹配,则将其发送到网关Web处理程序。此处理程序通过特定于请求的筛选器链运行请求。过滤器被虚线分割的原因是,过滤器可以在代理请求发送之前和之后运行逻辑。执行所有“预”过滤器逻辑。然后发出代理请求。在发出代理请求之后,运行“post”过滤器逻辑。
官方文档地址:
https://docs.spring.io/spring-cloud-gateway/docs/2.2.7.RELEASE/reference/html/
SpringCloud Gateway主要成员:Route(路由):网关的基本构建块。它由一个ID、一个目标URI、一组谓词和一组筛选器定义。如果聚合谓词为true,则匹配路由。Predicate(断言,即路由匹配规则):这是一个Java 8 Function Predicate。输入类型是springframework serverwebexchange。这允许您匹配来自HTTP请求的任何内容,例如头或参数。Filter(过滤器):这些是用特定工厂构建的Spring Framework GatewayFilter的实例。在这里,您可以在发送下游请求之前或之后修改请求和响应。
流程图:

二、SpringCloud Gateway使用和配置1、pom.xml引入依赖
主要的包是:spring-cloud-starter-gateway
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency. -->
<!--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
2、application.properties文件配置
基于Eureka为服务注册中心
server.port=8701
spring.application.name=SPRINGCLOUD-EUREKA-GATEWAY
#gateway路由配置
#使用服务发现路由
spring.cloud.gateway.discovery.locator.enabled=true
#服务路由名小写
spring.cloud.gateway.discovery.locator.lower-case-service-id=true
#设置路由id,没有固定规则,要求唯一,建设配合服务名
spring.cloud.gateway.routes[0].id=GATEWAY-SERVICE
#设置路由的uri,可以是调用的服务名,也可以请求的地址,当predicates匹配成功后,使用该路由的uri进行服务调用
#设置为服务名:lb://SPRINGCLOUD-EUREKA-SERVER
#设置为请求的地址:http://127.0.0.1:8601
#使用lb,有2个微服务,先启动一个,再启动gateway,然后再启动第二个微服务,未自动实现负载均衡;要先启动2个微服务后,再启动gateway,这样才能实现负载均衡
spring.cloud.gateway.routes[0].uri=lb://SPRINGCLOUD-EUREKA-SERVER
#设置路由断言,即调用的地址匹配的规则
#断言predicates的属性可以有:
#Path:Path=/**
#Cookie:Cookie=chocolate, ch.p,前面的为name,逗号后面的为值
#Header:Header=X-Request-Id, \d+,前面的为name,逗号后面的为值
#Host:Host=**.somehost.org,**.anotherhost.org
#Method:Method=GET
#Query:Query=aaa,请求参数必须有name为aaa的参数;Query=aaa, 111:请求参数必须有name为aaa的参数,且aaa参数的值为111;
#After:After=2021-03-17T15:47:51.534+08:00[Asia/Shanghai],日期时间,在该日期以后请求才被匹配,时间可以使用java.time.ZonedDateTime中的ZonedDateTime.now()获取当前时间
#Before:Before=2022-03-17T15:47:51.534+08:00[Asia/Shanghai],日期时间,在该日期之前才被匹配
#Between:Between=2021-03-17T15:47:51.534+08:00[Asia/Shanghai],2022-03-17T15:47:51.534+08:00[Asia/Shanghai],使用两个参数用逗号分隔,在两个时间范围内的请求才被匹配
#RemoteAddr:RemoteAddr=192.168.1.1/24
#断言方式一:
#/gateway/**:表示/gateway/路径下所有请求
#spring.cloud.gateway.routes[0].predicates[0].args.pattern=/**
#这个不能少,少了会报错:reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IllegalArgumentException: Unable to find RoutePredicateFactory with name gatewayTest
#spring.cloud.gateway.routes[0].predicates[0].name=Path
#断言方式二:请求微服务上的服务,方式一和方式二是2种不同的写法,方式一将规则分开,方式二写在一起
spring.cloud.gateway.routes[0].predicates[0]=Path=/test
#断言方式三:跳转到百度
spring.cloud.gateway.routes[1].id=GATEWAY-REDIRECT
spring.cloud.gateway.routes[1].uri=https://www.baidu.com
spring.cloud.gateway.routes[1].predicates[0]=Path=/redirect/**
spring.cloud.gateway.routes[1].filters[0].name=RedirectTo
spring.cloud.gateway.routes[1].filters[0].args.status=301
spring.cloud.gateway.routes[1].filters[0].args.url=https://www.baidu.com
#eureka实例名称
#eureka.instance.hostname=eureka8601.com
eureka.instance.instance-id=GATEWAY-8701
#路径显示IP地址
eureka.instance.prefer-ip-address=true
#eureka客户端向服务端发送心跳的时间间隔,单元为秒,默认为30秒
eureka.instance.lease-renewal-interval-in-seconds=2
#eureka服务端收到最后一次心跳等待的时间上限,超时将移除服务,单元为秒,默认为90秒
eureka.instance.lease-expiration-duration-in-seconds=5
#false表示向注册中心注册自己
eureka.client.register-with-eureka=true
#是否从Eureka抓取已有的注册信息,默认为true。单节点不用设置,集群必须设置为true,才能配置ribbon使用负载均衡
eureka.client.fetch-registry=true
#设置与Eureka server交互的地址查询服务和注册服务都需要依赖这个地址
eureka.client.service-url.defaultZone=http://eureka8501.com:8501/eureka
#集群配置
#eureka.client.service-url.defaultZone=http://eureka8501.com:8501/eureka,http://eureka8502.com:8501/eureka
3、启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class SpringCloud8701GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloud8701GatewayApplication.class, args);
}
}
三、springCloud Gateway routes predicates 配置方式
配置的方式有2种,1种是键值对的方式,一种是完全展开参数的方式
1、通过键值对的方式
使用两个参数定义Cookie路由,即Cookie名称mycookie和匹配mycookievalue的值。
application.yml文件的配置方式
快捷方式配置由筛选器名称、等号(=)和用逗号(,)分隔的参数值识别。
spring:
cloud:
gateway:
routes:
- id: cookie_route
uri: https://example.org
predicates:
- Cookie=mycookie,mycookievalue
application.properties文件的配置方式:
#设置路由id,没有固定规则,要求唯一,建设配合服务名
spring.cloud.gateway.routes[0].id=cookie_route
#设置路由的uri,可以是调用的服务名,也可以请求的地址,当predicates匹配成功后,使用该路由的uri进行服务调用
##设置为服务名:lb://SPRINGCLOUD-EUREKA-SERVER
#设置为请求的地址:http://127.0.0.1:8601
spring.cloud.gateway.routes[0].uri=https://example.org
spring.cloud.gateway.routes[0].predicates[0]=Cookie=mycookie,mycookievalue
2、完全展开的参数
完全展开的参数更像是带有名称/值对的标准yaml配置。通常,会有一个name键和一个args键。args键是用于配置谓词或筛选器的键值对的映射。
application.yml文件的配置方式
spring:
cloud:
gateway:
routes:
- id: cookie_route
uri: https://example.org
predicates:
- name: Cookie
args:
name: mycookie
regexp: mycookievalue
application.properties文件的配置方式:
spring.cloud.gateway.routes[0].id=cookie_route
spring.cloud.gateway.routes[0].uri=https://example.org
spring.cloud.gateway.routes[0].predicates[0].name=Cookie
spring.cloud.gateway.routes[0].predicates[0].args.name=mycookie
spring.cloud.gateway.routes[0].predicates[0].args.regexp=mycookievalue
四、springCloud Gateway predicates 详细配置
1、After route predicate
After route路由接受一个参数datetime(这是一个java分区日期时间)。此路由匹配在指定日期时间之后发生的请求,即在此时间后的请求才能正常访问。
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org
predicates:
- After=2017-01-20T17:42:47.789-07:00[America/Denver]
After=2017-01-20T17:42:47.789-07:00[America/Denver]中的时间可以使用java.time.ZonedDateTime中的ZonedDateTime.now()获取当前时间
具体示例:
import java.time.ZonedDateTime;
public class DatetimeUtil {
public static void main(String[] args) {
ZonedDateTime t = ZonedDateTime.now();
//2021-03-17T15:47:51.534+08:00[Asia/Shanghai]
System.out.println(t);
}
}
2、Before route predicate
Before route路由接受一个参数datetime(它是java分区的日期时间)。此路由匹配在指定日期时间之前发生的请求。
spring:
cloud:
gateway:
routes:
- id: before_route
uri: https://example.org
predicates:
- Before=2017-01-20T17:42:47.789-07:00[America/Denver]
3、Between route predicate
路由间接受两个参数,datetime1和datetime2,它们是java分区的日期时间对象。此谓词匹配发生在datetime1之后和datetime2之前的请求。datetime2参数必须在datetime1之后。
spring:
cloud:
gateway:
routes:
- id: between_route
uri: https://example.org
predicates:
- Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
4、Cookie route predicate
Cookie路由工厂接受两个参数,Cookie名称和regexp(这是一个Java正则表达式)。此路由匹配具有给定名称且其值与正则表达式匹配的cookie。
spring:
cloud:
gateway:
routes:
- id: cookie_route
uri: https://example.org
predicates:
- Cookie=chocolate, ch.p
5、Header route predicate
请求头路由有两个参数,头名称和regexp(这是一个Java正则表达式)。此路由与具有给定名称的标头匹配,该标头的值与正则表达式匹配。
spring:
cloud:
gateway:
routes:
- id: header_route
uri: https://example.org
predicates:
- Header=X-Request-Id, \d+
6、Host route predicate
主机路由采用一个参数:主机名模式列表。这个模式是一个蚂蚁风格的模式。作为分隔符。这个路由匹配与模式匹配的主机头。
spring:
cloud:
gateway:
routes:
- id: host_route
uri: https://example.org
predicates:
- Host=**.somehost.org,**.anotherhost.org
7、Method Route Predicate
方法路由接受一个methods参数,该参数是一个或多个参数:要匹配的HTTP方法。
spring:
cloud:
gateway:
routes:
- id: method_route
uri: https://example.org
predicates:
- Method=GET,POST
如果请求方法是GET或POST,则此路由匹配。
8、Path Route Predicate
路径路由工厂有两个参数:一个Spring路径匹配器模式列表和一个名为matchOptionalTrailingSeparator的可选标志。
spring:
cloud:
gateway:
routes:
- id: path_route
uri: https://example.org
predicates:
- Path=/red/{segment},/blue/{segment}
如果请求路径是:/red/1或/red/blue或/blue/green,则此路由匹配。
示例:
spring.cloud.gateway.routes[0].id=GATEWAY-SERVICE
spring.cloud.gateway.routes[0].uri=lb://SPRINGCLOUD-EUREKA-SERVER
spring.cloud.gateway.routes[0].predicates[0]=Path=/test
或者
spring.cloud.gateway.routes[0].predicates[0]=Path=/gateway/**
9、Query route predicate
查询路由有两个参数:一个必需的参数和一个可选的regexp(这是一个Java正则表达式)。
spring:
cloud:
gateway:
routes:
- id: query_route
uri: https://example.org
predicates:
- Query=green
如果请求参数中包含名称为green的参数,则路由匹配。
spring:
cloud:
gateway:
routes:
- id: query_route
uri: https://example.org
predicates:
- Query=red, gree.
如果请求参数中包含名称为green的参数,且值为red,则路由匹配。
10、RemoteAddr route predicate
远程Addr route获取源的列表(最小大小1),这些源是CIDR表示法(IPv4或IPv6)字符串,例如192.168.0.1/16(其中192.168.0.1是IP地址,16是子网掩码)。
spring:
cloud:
gateway:
routes:
- id: remoteaddr_route
uri: https://example.org
predicates:
- RemoteAddr=192.168.1.1/24
11、Weight route predicate
权重路由工厂有两个参数:group和Weight(int)。每组计算重量。
spring:
cloud:
gateway:
routes:
- id: weight_high
uri: https://weighthigh.org
predicates:
- Weight=group1, 8
- id: weight_low
uri: https://weightlow.org
predicates:
- Weight=group1, 2
四、springCloud Gateway GatewayFilter 详细配置
1、The AddRequestHeader GatewayFilter Factory
spring:
cloud:
gateway:
routes:
- id: add_request_header_route
uri: https://example.org
filters:
- AddRequestHeader=X-Request-red, blue
2、The AddRequestParameter GatewayFilter Factory
spring:
cloud:
gateway:
routes:
- id: add_request_parameter_route
uri: https://example.org
filters:
- AddRequestParameter=red, blue
3、The AddResponseHeader GatewayFilter Factory
spring:
cloud:
gateway:
routes:
- id: add_response_header_route
uri: https://example.org
filters:
- AddResponseHeader=X-Response-Red, Blue
4、The DedupeResponseHeader GatewayFilter Factory
spring:
cloud:
gateway:
routes:
- id: dedupe_response_header_route
uri: https://example.org
filters:
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
5、The RedirectTo GatewayFilter Factory
重定向到网关过滤器工厂需要两个参数,status和url。status参数应该是300系列重定向HTTP代码,例如301。url参数应该是有效的url。这是位置标头的值。对于相对重定向,应该使用uri:no://op作为路由定义的uri。
spring:
cloud:
gateway:
routes:
- id: prefixpath_route
uri: https://example.org
filters:
- RedirectTo=302, https://acme.org
示例:
#断言方式三:跳转到百度
spring.cloud.gateway.routes[1].id=GATEWAY-REDIRECT
spring.cloud.gateway.routes[1].uri=https://www.baidu.com
spring.cloud.gateway.routes[1].predicates[0]=Path=/redirect/**
spring.cloud.gateway.routes[1].filters[0].name=RedirectTo
spring.cloud.gateway.routes[1].filters[0].args.status=302
spring.cloud.gateway.routes[1].filters[0].args.url=https://www.baidu.com
其它的过滤器见官方文档:
https://docs.spring.io/spring-cloud-gateway/docs/2.2.7.RELEASE/reference/html/#gatewayfilter-factories
五、SpringCloud Gateway 自定义全局过滤器
@Bean
public GlobalFilter customFilter() {
return new CustomGlobalFilter();
}
public class CustomGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("custom global filter");
return chain.filter(exchange);
}
@Override
public int getOrder() {
return -1;
}
}
六、SpringCloud Gateway 超时配置
connect-timeout:必须以毫秒为单位指定连接超时。
response-timeout:响应超时必须指定为java.time.Duration文件
Http超时(响应和连接)可以为所有路由配置,并为每个特定路由重写。
1、全局超时配置
spring:
cloud:
gateway:
httpclient:
connect-timeout: 1000
response-timeout: 5s
2、单个路由超时配置
- id: per_route_timeouts
uri: https://example.org
predicates:
- name: Path
args:
pattern: /delay/{timeout}
metadata:
response-timeout: 200
connect-timeout: 200
七、SpringCloud Gateway 跨域配置
可以配置网关来控制CORS行为。“全局”CORS配置是URL模式到Spring框架CORS配置的映射
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "https://docs.spring.io"
allowedMethods:
- GET
在示例中,允许来自docs.spring.io对于所有GET请求的路径。
(时间宝贵,分享不易,捐赠回馈,^_^)
================================
©Copyright 蕃薯耀 2021-03-18
https://www.cnblogs.com/fanshuyao/