# spring cloud gateway ## 项目引入spring cloud gateway 如果要在项目中引入spring cloud gateway,可以在项目pom文件中添加如下依赖: ```xml org.springframework.cloud spring-cloud-starter-gateway ``` > 如果已经在项目中引入了spring-cloud-starter-gateway的依赖,但是不想启用gateway,可以在配置文件中指定`spring.cloud.gateway.enabled=false` > Spring Cloud gateway在运行时需要netty作为运行时环境,并且采用Spring Webflux构建,gateway在传统的基于servlet的环境中无法运行。 ## Spring Cloud gateway核心概念 - Route:gateway的基本构建单元,Route由一个id、一个目标uri,predicate集合、filter集合组成。如果聚合predicate为true,那么route被匹配到 - Predicate:Predicate的输入是` Spring Framework ServerWebExchange`,通过该输入,可以匹配http请求中的任何内容,如header或请求参数等 - Filter:其是GatewayFilter的实例,通过特定的factory构造。在filter中,可以在发送到下游请求之前或者之后对request和response进行修改。 ## Spring Cloud Gateway如何工作 1. 客户端向spring cloud gateway发送请求,如果Gateway Handler Mapping将请求匹配到route,那么会向gateway web handler发送请求 2. gateway web handler通过filter chain对请求进行处理 ## 配置route predicate factories和gateway filter factories 有两种方式来配置predicate和filter:shortcuts和全展开参数 ### shortcut配置方式 ```yml spring: cloud: gateway: routes: - id: after_route uri: https://example.org predicates: - Cookie=mycookie,mycookievalue ``` ## Route Predicate Factories Spring Cloud Gateway包含了许多内置的route predicate factories,所有的这些predicate都匹配到http请求的不同属性。可以通过逻辑运算符`and`将多个route predicate factory组合起来。 ### After Route Predicate Factory After Route Predicate Factory接收一个参数`datetime`,该参数为ZonedDateTime类型,该Predicate匹配发生在指定时间之后的请求。 ```yml spring: cloud: gateway: routes: - id: after_route uri: https://example.org predicates: - After=2017-01-20T17:42:47.789-07:00[America/Denver] ``` 该route匹配2017-01-20T17:42:47.789-07:00[America/Denver]该时间之后的任意请求 ###