# 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]该时间之后的任意请求 ### Before Route Predicate Factory Before route predicate factory接收一个`datetime`参数,参数为ZonedDateTime类型,该predicate匹配发生在某时间之前的请求。 ```yml spring: cloud: gateway: routes: - id: before_route uri: https://example.org predicates: - Before=2017-01-20T17:42:47.789-07:00[America/Denver] ``` 该route匹配发生在2017-01-20T17:42:47.789-07:00[America/Denver]之前的任意请求 ### Between Route Predicate Factory Between Route Predicate Factory接收两个参数,都是ZonedDateTime类型,该predicate匹配发生在datetime1和datetime2之间的请求,其中第二个参数指定的时间必须位于第一个参数指定时间之后。如下指定了一个between predicate示例: ```yml 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] ``` ### Cookie Route Predicate Factory Cookie Route Predicate Factory接收两个参数,`name`和`regexp`。该predicate匹配请求中含有指定名称,并且cookie值满足`regexp`正则表达式。如下展示了一个cookie predicate示例: ```xml spring: cloud: gateway: routes: - id: cookie_route uri: https://example.org predicates: - Cookie=chocolate, ch.p ``` 上述cookie_route会匹配请求中含有name为chocolate的cookie,并且cookie值满足`ch.p`正则表达式的请求。 ### Header Route Predicate Factory Header Route Predicate Factory接收两个参数,`header`和`regexp`。