Files
rikako-note/spring/Spring Cloud/Spring Cloud gateway.md

2.4 KiB
Raw Blame History

spring cloud gateway

项目引入spring cloud gateway

如果要在项目中引入spring cloud gateway可以在项目pom文件中添加如下依赖

<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>

如果已经在项目中引入了spring-cloud-starter-gateway的依赖但是不想启用gateway可以在配置文件中指定spring.cloud.gateway.enabled=false

Spring Cloud gateway在运行时需要netty作为运行时环境并且采用Spring Webflux构建gateway在传统的基于servlet的环境中无法运行。

Spring Cloud gateway核心概念

  • Routegateway的基本构建单元Route由一个id、一个目标uripredicate集合、filter集合组成。如果聚合predicate为true那么route被匹配到
  • PredicatePredicate的输入是 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和filtershortcuts和全展开参数

shortcut配置方式

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匹配发生在指定时间之后的请求。

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]该时间之后的任意请求