如需转载,请根据 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 许可,附上本文作者及链接。
本文作者: 执笔成念
作者昵称: zbcn
本文链接: https://1363653611.github.io/zbcn.github.io/2021/01/12/springcloud-12gateway%E7%BD%91%E5%85%B3/
Spring Cloud Gateway:新一代API网关服务
Spring Cloud Gateway 为 SpringBoot 应用提供了API网关支持,具有强大的智能路由与过滤器功能,本文将对其用法进行详细介绍。
Gateway 简介
Gateway是在Spring生态系统之上构建的API网关服务,基于Spring 5,Spring Boot 2和 Project Reactor等技术。Gateway旨在提供一种简单而有效的方式来对API进行路由,以及提供一些强大的过滤器功能, 例如:熔断、限流、重试等。
Spring Cloud Gateway 具有如下特性:
- 基于Spring Framework 5, Project Reactor 和 Spring Boot 2.0 进行构建;
- 动态路由:能够匹配任何请求属性;
- 可以对路由指定 Predicate(断言)和 Filter(过滤器);
- 集成Hystrix的断路器功能;
- 集成 Spring Cloud 服务发现功能;
- 易于编写的 Predicate(断言)和 Filter(过滤器);
- 请求限流功能;
- 支持路径重写。
相关概念
- Route(路由):路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如果断言为true则匹配该路由;
- Predicate(断言):指的是Java 8 的 Function Predicate。 输入类型是Spring框架中的ServerWebExchange。 这使开发人员可以匹配HTTP请求中的所有内容,例如请求头或请求参数。如果请求与断言相匹配,则进行路由;
- Filter(过滤器):指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前后对请求进行修改。
创建 api-gateway模块
这里我们创建一个api-gateway模块来演示Gateway的常用功能。
在pom.xml中添加相关依赖
1 | <dependency> |
2 | <groupId>org.springframework.cloud</groupId> |
3 | <artifactId>spring-cloud-starter-gateway</artifactId> |
4 | </dependency> |
两种不同的配置路由方式
Gateway 提供了两种不同的方式用于配置路由,一种是通过yml文件来配置,另一种是通过Java Bean来配置,下面我们分别介绍下。
使用yml配置
- 在application.yml中进行配置:
1 | server: |
2 | port: 9201 |
3 | service-url: |
4 | user-service: http://localhost:9001 |
5 | spring: |
6 | cloud: |
7 | gateway: |
8 | routes: |
9 | - id: path_route #路由的ID |
10 | uri: ${service-url.user-service}/user/{id} #匹配后路由地址 |
11 | predicates: # 断言,路径相匹配的进行路由 |
12 | - Path=/user/{id} |
- 启动eureka-server,user-service和api-gateway服务,并调用该地址测试:http://localhost:9201/user/1
- 我们发现该请求被路由到了user-service的该路径上:http://localhost:8201/user/1
使用Java Bean配置
- 添加相关配置类,并配置一个RouteLocator对象:
1 | |
2 |
|
3 | public class GatewayConfig { |
4 | |
5 | |
6 | public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { |
7 | return builder.routes() |
8 | .route("path_route2", r -> r.path("/user/getByUsername") |
9 | .uri("http://localhost:8201/user/getByUsername")) |
10 | .build(); |
11 | } |
12 | } |
- 重新启动api-gateway服务,并调用该地址测试:http://localhost:9201/user/getByUsername?username=zbcn
- 我们发现该请求被路由到了user-service的该路径上:http://localhost:8201/user/getByUsername?username=zbcn
Route Predicate 的使用
Spring Cloud Gateway将路由匹配作为Spring WebFlux HandlerMapping基础架构的一部分。 Spring Cloud Gateway包括许多内置的Route Predicate工厂。 所有这些Predicate都与HTTP请求的不同属性匹配。 多个Route Predicate工厂可以进行组合,下面我们来介绍下一些常用的Route Predicate。
注意:Predicate中提到的配置都在application-predicate.yml文件中进行修改,并用该配置启动api-gateway服务。
After Route Predicate
在指定时间之后的请求会匹配该路由。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: after_route |
6 | uri: ${service-url.user-service} |
7 | predicates: |
8 | - After=2019-09-24T16:30:00+08:00[Asia/Shanghai] |
Before Route Predicate
在指定时间之前的请求会匹配该路由。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: before_route |
6 | uri: ${service-url.user-service} |
7 | predicates: |
8 | - Before=2019-09-24T16:30:00+08:00[Asia/Shanghai] |
Between Route Predicate
在指定时间区间内的请求会匹配该路由。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: before_route |
6 | uri: ${service-url.user-service} |
7 | predicates: |
8 | - Between=2019-09-24T16:30:00+08:00[Asia/Shanghai], 2019-09-25T16:30:00+08:00[Asia/Shanghai] |
Cookie Route Predicate
带有指定Cookie的请求会匹配该路由。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: cookie_route |
6 | uri: ${service-url.user-service} |
7 | predicates: |
8 | - Cookie=username,macro |
使用curl工具发送带有cookie为username=macro
的请求可以匹配该路由。
1 | curl http://localhost:9201/user/1 --cookie "username=zbcn" |
Header Route Predicate
带有指定请求头的请求会匹配该路由。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: header_route |
6 | uri: ${service-url.user-service} |
7 | predicates: |
8 | - Header=X-Request-Id, \d+ |
使用curl工具发送带有请求头为X-Request-Id:123
的请求可以匹配该路由。
1 | curl http://localhost:9201/user/1 -H "X-Request-Id:123" |
Host Route Predicate
带有指定Host的请求会匹配该路由。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: host_route |
6 | uri: ${service-url.user-service} |
7 | predicates: |
8 | - Host=**.zbcna.top |
- 使用curl工具发送带有请求头为
Host:www.zcna.top
的请求可以匹配该路由。
1 | curl http://localhost:9201/user/1 -H "Hostwww.zcna.top" |
Method Route Predicate
发送指定方法的请求会匹配该路由。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: method_route |
6 | uri: ${service-url.user-service} |
7 | predicates: |
8 | - Method=GET |
使用curl工具发送GET请求可以匹配该路由。
1 | curl http://localhost:9201/user/1 |
使用curl工具发送POST请求无法匹配该路由。
1 | curl -X POST http://localhost:9201/user/1 |
Path Route Predicate
发送指定路径的请求会匹配该路由。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: path_route |
6 | uri: ${service-url.user-service}/user/{id} |
7 | predicates: |
8 | - Path=/user/{id} |
使用curl工具发送/user/1
路径请求可以匹配该路由。
1 | curl http://localhost:9201/user/1Copy to clipboardErrorCopied |
使用curl工具发送/abc/1
路径请求无法匹配该路由。
1 | curl http://localhost:9201/abc/1 |
Query Route Predicate
带指定查询参数的请求可以匹配该路由。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: query_route |
6 | uri: ${service-url.user-service}/user/getByUsername |
7 | predicates: |
8 | - Query=username |
使用curl工具发送带`username=zbcn查询参数的请求可以匹配该路由。
1 | curl http://localhost:9201/user/getByUsername?username=zbcn |
使用curl工具发送带不带查询参数的请求无法匹配该路由。
1 | curl http://localhost:9201/user/getByUsername |
RemoteAddr Route Predicate
从指定远程地址发起的请求可以匹配该路由。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: remoteaddr_route |
6 | uri: ${service-url.user-service} |
7 | predicates: |
8 | - RemoteAddr=192.168.1.1/24 |
使用curl工具从192.168.1.1发起请求可以匹配该路由。
1 | curl http://localhost:9201/user/1 |
Weight Route Predicate
使用权重来路由相应请求,以下表示有80%的请求会被路由到localhost:8201,20%会被路由到localhost:8202。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: weight_high |
6 | uri: http://localhost:8201 |
7 | predicates: |
8 | - Weight=group1, 8 |
9 | - id: weight_low |
10 | uri: http://localhost:8202 |
11 | predicates: |
12 | - Weight=group1, 2 |
Route Filter 的使用
路由过滤器可用于修改进入的HTTP请求和返回的HTTP响应,路由过滤器只能指定路由进行使用。Spring Cloud Gateway 内置了多种路由过滤器,他们都由GatewayFilter的工厂类来产生,下面我们介绍下常用路由过滤器的用法。
1 | spring.cloud.gateway.routes.*:配置路由信息 |
2 | id:路由唯一标识 |
3 | uri:路由转发地址,以 lb 开头的路由,会由 ribbon 处理,转发到 cloud-eureka-client 的服务处理。也可配置成 http 的单机路由 — http://localhost:2222。 |
4 | order:路由执行顺序(也可理解成过滤器的执行顺序),执行顺序是从小到大执行,较高的值被解释为较低的优先级。 |
5 | predicates:路由断言,匹配访问路径为 "/client/**" 的请求。 |
6 | filters:网关的过滤器配置 |
AddRequestParameter GatewayFilter
给请求添加参数的过滤器。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: add_request_parameter_route |
6 | uri: http://localhost:8201 |
7 | filters: |
8 | - AddRequestParameter=username, zncn |
9 | predicates: |
10 | - Method=GET |
以上配置会对GET请求添加username=zbcn
的请求参数,通过curl工具使用以下命令进行测试。
1 | curl http://localhost:9201/user/getByUsername |
相当于发起该请求:
1 | curl http://localhost:8201/user/getByUsername?username=zbcn |
StripPrefix GatewayFilter
对指定数量的路径前缀进行去除的过滤器。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: strip_prefix_route |
6 | uri: http://localhost:8201 |
7 | predicates: |
8 | - Path=/user-service/** |
9 | filters: |
10 | - StripPrefix=2 |
以上配置会把以/user-service/
开头的请求的路径去除两位,通过curl工具使用以下命令进行测试。
1 | curl http://localhost:9201/user-service/a/user/1 |
相当于发起该请求:
1 | curl http://localhost:8201/user/1 |
PrefixPath GatewayFilter
与StripPrefix过滤器恰好相反,会对原有路径进行增加操作的过滤器。
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: prefix_path_route |
6 | uri: http://localhost:8201 |
7 | predicates: |
8 | - Method=GET |
9 | filters: |
10 | - PrefixPath=/user |
以上配置会对所有GET请求添加/user
路径前缀,通过curl工具使用以下命令进行测试。
1 | curl http://localhost:9201/1 |
相当于发起该请求:
1 | curl http://localhost:8201/user/1 |
Hystrix GatewayFilter
Hystrix 过滤器允许你将断路器功能添加到网关路由中,使你的服务免受级联故障的影响,并提供服务降级处理。
- 要开启断路器功能,我们需要在pom.xml中添加Hystrix的相关依赖:
1 | <dependency> |
2 | <groupId>org.springframework.cloud</groupId> |
3 | <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> |
4 | </dependency> |
- 然后添加相关服务降级的处理类:
1 |
|
2 | public class FallbackController { |
3 | |
4 | "/fallback") ( |
5 | public Object fallback() { |
6 | Map<String,Object> result = new HashMap<>(); |
7 | result.put("data",null); |
8 | result.put("message","Get request fallback!"); |
9 | result.put("code",500); |
10 | return result; |
11 | } |
12 | } |
- 在application-filter.yml中添加相关配置,当路由出错时会转发到服务降级处理的控制器上:
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: hystrix_route |
6 | uri: ${service-url.user-service} |
7 | order: 0 # 路由执行顺序(也可理解成过滤器的执行顺序),执行顺序是从小到大执行,较高的值被解释为较低的优先级。 |
8 | predicates: |
9 | - Method=GET |
10 | filters: |
11 | - name: Hystrix |
12 | args: |
13 | name: fallbackcmd |
14 | fallbackUri: forward:/fallback |
- 关闭user-service,调用该地址进行测试:http://localhost:9201/user/1 ,发现已经返回了服务降级的处理信息。
RequestRateLimiter GatewayFilter
RequestRateLimiter 过滤器可以用于限流,使用RateLimiter实现来确定是否允许当前请求继续进行,如果请求太大默认会返回HTTP 429-太多请求状态。
- 在pom.xml中添加相关依赖:
1 | <dependency> |
2 | <groupId>org.springframework.boot</groupId> |
3 | <artifactId>spring-boot-starter-data-redis-reactive</artifactId> |
4 | </dependency> |
- 添加限流策略的配置类,这里有两种策略一种是根据请求参数中的username进行限流,另一种是根据访问IP进行限流;
1 |
|
2 | public class RedisRateLimiterConfig { |
3 | |
4 | |
5 | public KeyResolver userKeyResolver() { |
6 | return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("username")); |
7 | } |
8 | |
9 | |
10 | |
11 | public KeyResolver ipKeyResolver() { |
12 | return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName()); |
13 | } |
14 | } |
- 我们使用Redis来进行限流,所以需要添加Redis和RequestRateLimiter的配置,这里对所有的GET请求都进行了按IP来限流的操作;
- 新建配置文件 application-limit.yml。添加如下配置
1 | server: |
2 | port: 9201 |
3 | service-url: |
4 | user-service: http://localhost:9001 |
5 | spring: |
6 | cloud: |
7 | gateway: |
8 | routes: |
9 | - id: requestratelimiter_route # 限流 |
10 | uri: ${service-url.user-service} |
11 | order: 0 |
12 | filters: |
13 | - name: RequestRateLimiter |
14 | args: |
15 | redis-rate-limiter.replenishRate: 1 #每秒允许处理的请求数量 |
16 | redis-rate-limiter.burstCapacity: 2 #每秒最大处理的请求数量 |
17 | key-resolver: "#{@ipKeyResolver}" #限流策略,对应策略的Bean |
18 | predicates: |
19 | - Method=GET |
20 | logging: |
21 | level: |
22 | org.springframework.cloud.gateway: debug |
23 | redis: |
24 | host: localhost |
25 | port: 6379 |
26 | # password: 123456 |
27 | logging: |
28 | level: |
29 | org.springframework.cloud.gateway: debug |
- 利用 application-limit.yml 启动 服务
1 | --spring.config.location=classpath:application-limit.yml |
- 多次请求该地址:http://localhost:9201/user/1 ,会返回状态码为429的错误;
Retry GatewayFilter
- 对路由请求进行重试的过滤器,可以根据路由请求返回的HTTP状态码来确定是否进行重试。
- 修改配置文件:
1 | spring: |
2 | cloud: |
3 | gateway: |
4 | routes: |
5 | - id: retry_route |
6 | uri: http://localhost:9001 |
7 | predicates: |
8 | - Method=GET |
9 | filters: |
10 | - name: Retry |
11 | args: |
12 | retries: 1 #需要进行重试的次数 |
13 | statuses: BAD_GATEWAY #返回哪个状态码需要进行重试,返回状态码为5XX进行重试 |
14 | backoff: |
15 | firstBackoff: 10ms |
16 | maxBackoff: 50ms |
17 | factor: 2 |
18 | basedOnPreviousValue: false |
- 当调用返回500时会进行重试,访问测试地址:http://localhost:9201/user/111
- 可以发现user-service控制台报错2次,说明进行了一次重试。
结合注册中心使用
之前使用Zuul作为网关结合注册中心进行使用时,默认情况下Zuul会根据注册中心注册的服务列表,以服务名为路径创建动态路由,Gateway同样也实现了该功能。下面我们演示下Gateway结合注册中心如何使用默认的动态路由和过滤器。
使用动态路由
- 在pom.xml中添加相关依赖:
1 | <dependency> |
2 | <groupId>org.springframework.cloud</groupId> |
3 | <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> |
4 | </dependency> |
- 添加application-eureka.yml配置文件:
1 | server: |
2 | port: 9201 |
3 | spring: |
4 | application: |
5 | name: api-gateway |
6 | cloud: |
7 | gateway: |
8 | discovery: |
9 | locator: |
10 | enabled: true #开启从注册中心动态创建路由的功能 |
11 | lower-case-service-id: true #使用小写服务名,默认是大写 |
12 | eureka: |
13 | client: |
14 | service-url: |
15 | defaultZone: http://localhost:8001/eureka/ |
16 | logging: |
17 | level: |
18 | org.springframework.cloud.gateway: debug |
- 使用application-eureka.yml配置文件启动api-gateway服务,访问http://localhost:9201/user-service/user/1 ,可以路由到user-service的http://localhost:8201/user/1 处。
使用过滤器
在结合注册中心使用过滤器的时候,我们需要注意的是uri的协议为lb
,这样才能启用Gateway的负载均衡功能。
- 修改application-eureka.yml文件,使用了PrefixPath过滤器,会为所有GET请求路径添加
/user
路径并路由;
1 | server: |
2 | port: 9201 |
3 | service-url: |
4 | user-service: lb://user-service #此处需要使用lb协议 |
5 | spring: |
6 | application: |
7 | name: api-gateway |
8 | cloud: |
9 | gateway: |
10 | routes: |
11 | - id: user_server_route #路由的ID |
12 | uri: ${service-url.user-service} #匹配后路由地址 |
13 | order: 10 # 路由执行顺序(也可理解成过滤器的执行顺序),执行顺序是从小到大执行,较高的值被解释为较低的优先级。 |
14 | predicates: # 断言,路径相匹配的进行路由 |
15 | - Path=/user/{id} |
16 | filters: |
17 | - name: Hystrix # 熔断(如果服务失败,则熔断) |
18 | args: |
19 | name: fallbackcmd |
20 | fallbackUri: forward:/fallback |
21 | - name: Retry # 重复请求 |
22 | args: |
23 | retries: 1 #需要进行重试的次数 |
24 | statuses: BAD_GATEWAY #返回哪个状态码需要进行重试,返回状态码为5XX进行重试 |
25 | backoff: |
26 | firstBackoff: 10ms |
27 | maxBackoff: 50ms |
28 | factor: 2 |
29 | basedOnPreviousValue: false |
30 | - name: RequestRateLimiter # 限流 |
31 | args: |
32 | redis-rate-limiter.replenishRate: 1 #每秒允许处理的请求数量 |
33 | redis-rate-limiter.burstCapacity: 2 #每秒最大处理的请求数量 |
34 | key-resolver: "#{@ipKeyResolver}" #限流策略,对应策略的Bean |
35 | # 注册中心 |
36 | eureka: |
37 | client: |
38 | service-url: |
39 | defaultZone: http://localhost:8000/eureka/ |
40 | register-with-eureka: true |
41 | fetch-registry: true |
42 | |
43 | profiles: |
44 | active: dev |
45 | |
46 | redis: |
47 | host: localhost |
48 | port: 6379 |
49 | # password: 123456 |
50 | logging: |
51 | level: |
52 | org.springframework.cloud.gateway: debug |
- 使用application-eureka.yml配置文件启动api-gateway服务,访问http://localhost:9201/1 ,可以路由到user-service的http://localhost:8201/user/1 处。
1 | --spring.config.location=classpath:application-eureka.yml |
使用到的模块
1 | ZBCN-SERVER |
2 | ├── zbcn-register/eureka-server -- eureka注册中心 |
3 | ├── zbcn-gateway/api-gateway -- gateway作为网关服务 |
4 | └── zbcn-business/user-server -- 业务客户端 |