1简介
Spring Cloud Gateway 为 SpringBoot 应用提供了API网关支持,具有强大的智能路由与过滤器功能,本文将对其用法进行详细介绍
三要素
Route(路由)
路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如果断言为true则匹配该路由
Predicate(断言)
判断请求的转发条件
After Route Predicate
在指定时间之后的请求会匹配该路由。
Before Route Predicate
在指定时间之前的请求会匹配该路由。
Cookie Route Predicate
带有指定Cookie的请求会匹配该路由。
Header Route Predicate
带有指定请求头的请求会匹配该路由。
Filter(过滤)
指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改。
2快速搭建
pom 配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springcloud-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springcloud-gateway</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--webflux 依赖 ,gateway 使用的是webflux,并没有使用springmvc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR8</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
yml配置
server:
port: 8080
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
- id: "server_v1"
uri: "https://www.baidu.com"
predicates:
- Path=/api/**
访问
跳转到
3其他功能
After Route Predicate
在指定时间之后的请求会匹配该路由
spring:
cloud:
gateway:
routes:
- id: after_route
uri: ${service-url.service-name}
predicates:
- After=2021-08-24T12:30:00+08:00[Asia/Shanghai]
2Before Route Predicate
在指定时间之前的请求会匹配该路由
spring:
cloud:
gateway:
routes:
- id: before_route
uri: ${service-url.service-name}
predicates:
- Before=2021-08-18T12:30:00+08:00[Asia/Shanghai]
3Cookie Route Predicate
带有指定Cookie的请求会匹配该路由。
spring:
cloud:
gateway:
routes:
- id: cookie route
uri: ${service-url.service-name}
predicates:
- Cookie=userxxx
4Header Route Predicate
带有指定请求头的请求会匹配该路由。
spring:
cloud:
gateway:
routes:
- id: header route
uri: ${service-url.service-name}
predicates:
- Header=xxxx