下载源码:https://gitee.com/ctocloud/spring-cloud-poetry.git
定义
Gateway是spring cloud 推出的新的网关路由,它关注于安全性,网关路由,限流控制等,是第二代网关路由器。
断言路由
Spring cloud gateway 内置许多断言工厂,这些断言匹配不同的HTTP请求属性。多种路由可以相互组合。
例子源码请参见
源码及测试:
首先启动 cloud-eureka,cloud-service,新建cloud-gateway,pom文件新增依赖spring-cloud-starter-gateway
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
After Route Predicate Factory:接受一个时间参数,满足时间之后能路由。配置文件 application.yum。
spring:
cloud:
gateway:
routes:
- id: after_route
uri: http://localhost:8085/hello
predicates:
- After=2018-04-20T17:42:47.789-07:00[America/Denver]
id:表示路由名称
uri:路由转发的地址
predicates:断言规则
After:表示是满足时间之后
这时候如果当前时间是2019/03/14,配置的是2018/03/14。这时候访问localhost:8080,
请求不会被拦截正常访问。如果配置的是2020/03/04,请求会被拦截。
Before Route Predicate Factory:满足时间之后路由,同上面例子。
spring:
cloud:
gateway:
routes:
- id: before_route
uri: http://localhost:8085/hello
predicates:
- Before=2018-04-20T17:42:47.789-07:00[America/Denver]
Between Route Predicate Factory:满足在时间A和时间B之间路由,同上面例子。
spring:
cloud:
gateway:
routes:
- id: between_route
uri: http://localhost:8085/hello
predicates:
- Between=2018-04-20T17:42:47.789-07:00[America/Denver],2019-04-20T17:42:47.789-07:00[America/Denver]
Cookie Route Predicate Factory:满足cookie的匹配规则路由。
spring:
cloud:
gateway:
routes:
- id: cookie_route
uri: http://localhost:8085/hello
predicates:
- Cookie=name,test
如上图 coockie的名字是name值是test允许路由,
如果用postman直接访问localhost:8080,请求是会被拦截报错404。
如果为localhost域名name=test的coockie,请求通过。
Header Route Predicate Factory:请求头配置路由。
spring:
cloud:
gateway:
routes:
- id: header_route
uri: http://localhost:8085/hello
predicates:
- Header=X-Request-Id,\d+
如上图请求头 header中带 X-Request-Id,且值为数字,允许路由。
用postman直接请求localhost:8080请求被拦截,如果加一个headers name为X-Request-Id value为1,请求通过。
Host Route Predicate Factory:域名匹配规则路由。
spring:
cloud:
gateway:
routes:
- id: host_route
uri: http://localhost:8085/hello
predicates:
- Host=**.baidu.org
Method Route Predicate Factory:请求方法规则路由,如下图只有GET方法会被路由,其他方式被拦截。
spring:
cloud:
gateway:
routes:
- id: method_route
uri: http://localhost:8085/hello
predicates:
- Method=GET
Path Route Predicate Factory:路径规则路由,只有匹配如下规则的路径可以路由。
spring:
cloud:
gateway:
routes:
- id: path_route
uri: http://localhost:8085/hello
predicates:
- Path=/test/{name}
Query Route Predicate Factory:查询参数规则路由,如下图,只有参数中name=test的可以路由。
spring:
cloud:
gateway:
routes:
- id: query_route
uri: http://localhost:8085/hello
predicates:
- Query=name,test.
RemoteAddr Route Predicate Factory:ip地址规则路由,满足ip规则的请求路由。
spring:
cloud:
gateway:
routes:
- id: remoteaddr_route
uri: http://localhost:8085/hello
predicates:
- RemoteAddr=192.168.1.1