一、什么是Spring Cloud Gateway?
-
Spring Cloud Gateway 为 SpringBoot 应用提供了API网关支持,具有强大的路由转发与过滤器功能。
-
Spring Cloud Gateway 是在Spring生态系统之上构建的API网关服务,基于Spring 5,Spring Boot 2和 Project Reactor等技术。
-
Spring Cloud Gateway 旨在提供一种简单而有效的方式来对API进行路由,以及提供一些强大的过滤器功能, 例如:熔断、限流、重试等。
二、相关功能
- 基于Spring Framework 5, Project Reactor 和 Spring Boot 2.0 进行构建
- 自身通过Spring Cloud Zuul组件进行改进,效率要比Zull组件高很多
- 具有动态路由功能,能够匹配任何请求属性
- 可以对路由指定 Predicate(断言)和 Filter(过滤器)
- 集成Hystrix的断路器功能
- 集成 Spring Cloud 服务发现功能
- 易于编写的 Predicate(断言)和 Filter(过滤器)
- 请求限流功能
- 支持路径重写
三、相关概念
-
Route(路由)
路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如果断言为true则匹配该路由。
-
Predicate(断言)
指的是Java 8 的 Function Predicate。 输入类型是Spring框架中的ServerWebExchange。 这使开发人员可以匹配HTTP请求中的所有内容,例如请求头或请求参数。如果请求与断言相匹配,则进行路由。
-
Filter(过滤器)
指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前后对请求进行修改。
四、路由转发项目搭建
-
添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
-
添加配置
-
配置文件方式
server: port: 8080 spring: application: name: consul-gateway cloud: consul: host: localhost port: 8500 discovery: service-name: ${spring.application.name} gateway: routes: # 服务名称 - id: consul-service1 # 服务地址 uri: http://localhost:8081/ # 设置断言,路径相匹配的进行路由 predicates: - Path=/service1/**
-
配置类方式
@Configuration public class GatewayConfig { @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route( "consul-service1", r -> r.path("/service1/**").uri("http://localhost:8081/") ) .route( "consul-service2", r -> r.path("/service2/**").uri("http://localhost:8082/") ) .build(); } }
-
-
测试
# 访问:http://localhost:8080/service1/show
-
查看路由配置信息
添加配置
management: endpoints: web: exposure: include: '*'
# 访问:http://localhost:8080/actuator/gateway/routes
五、实现负载均衡
-
添加配置
server: port: 8080 spring: application: name: consul-gateway cloud: consul: host: localhost port: 8500 discovery: service-name: ${spring.application.name} gateway: routes: - id: user-service # 服务地址 uri: lb://user-service predicates: - Path=/user/** # 开启负载均衡 discovery: locator: enabled: true lower-case-service-id: true
-
测试
启动两个user-service服务,通过访问:http://localhost:8080/user/show 观察控制台打印结果。
六、路由断言Predicate
Spring Cloud Gateway将路由匹配作为Spring WebFlux HandlerMapping基础架构的一部分,Predicate的触发是在进行路由过滤之前进行。
Spring Cloud Gateway包括许多内置的Route Predicate工厂,这些Predicate都与HTTP请求的不同属性匹配,多个Route Predicate工厂还可以进行组合。
-
Before Route Predicate
在指定时间之前的请求会匹配该路由。
// 查看当前时区 System.out.println(ZonedDateTime.now())
spring: cloud: gateway: routes: - id: before_route uri: ${service-url.user-service} predicates: - Before=2019-09-24T16:30:00+08:00[Asia/Shanghai]
-
After Route Predicate
在指定时间之后的请求会匹配该路由。
spring: cloud: gateway: routes: - id: before_route uri: ${service-url.user-service} predicates: - After=2019-09-24T16:30:00+08:00[Asia/Shanghai]
-
Between Route Predicate
在指定时间区间内的请求会匹配该路由。
spring: cloud: gateway: routes: - id: before_route uri: ${service-url.user-service} predicates: - Between=2019-09-24T16:30:00+08:00[Asia/Shanghai], 2019-09- 25T16:30:00+08:00[Asia/Shanghai]
-
Cookie Route Predicate
带有指定Cookie的请求会匹配该路由。
spring: cloud: gateway: routes: - id: before_route uri: ${service-url.user-service} predicates: - Cookie=username,zhangsan
使用curl工具发送带有cookie为
username=zhangsan
的请求可以匹配该路由。curl http://localhost:9201/user/1 --cookie "username=zhangsan"
-
Header Route Predicate
带有指定请求头的请求会匹配该路由 。
spring: cloud: gateway: routes: - id: before_route uri: ${service-url.user-service} predicates: - Header=X-Request-Id, \d+
使用curl工具发送带有请求头为
X-Request-Id:123
的请求可以匹配该路由。curl http://localhost:9201/user/1 -H "X-Request-Id:123"
-
Host Route Predicate
带有指定Host的请求会匹配该路由 。
spring: cloud: gateway: routes: - id: before_route uri: ${service-url.user-service} predicates: - Host=**.prochick.com
使用curl工具发送带有请求头为
Host:www.prochick.com
的请求可以匹配该路由。curl http://localhost:9201/user/1 -H "Host:www.prochick.com"
-
Method Route Predicate
发送指定方法的请求会匹配该路由 。
spring: cloud: gateway: routes: - id: before_route uri: ${service-url.user-service} predicates: - Method=GET
使用curl工具发送GET请求可以匹配该路由。
curl http://localhost:9201/user/1
使用curl工具发送POST请求无法匹配该路由。
curl -X POST http://localhost:9201/user/1
-
Path Route Predicate
发送指定路径的请求会匹配该路由 。
spring: cloud: gateway: routes: - id: before_route uri: ${service-url.user-service} predicates: - Path=/user/{id}
使用curl工具发送
/user/1
路径请求可以匹配该路由。curl http://localhost:9201/user/1 复制代码
使用curl工具发送
/abc/1
路径请求无法匹配该路由。curl http://localhost:9201/abc/1
-
Query Route Predicate
带指定查询参数的请求可以匹配该路由 。
spring: cloud: gateway: routes: - id: before_route uri: ${service-url.user-service} predicates: - Query=username
使用curl工具发送带
username=macro
查询参数的请求可以匹配该路由。curl http://localhost:9201/user/getByUsername?username=macro 复制代码
使用curl工具发送带不带查询参数的请求无法匹配该路由。
curl http://localhost:9201/user/getByUsername
-
RemoteAddr Route Predicate
从指定远程地址发起的请求可以匹配该路由 。
spring: cloud: gateway: routes: - id: before_route uri: ${service-url.user-service} predicates: - RemoteAddr=192.168.1.1/24
使用curl工具从192.168.1.1发起请求可以匹配该路由。
curl http://localhost:9201/user/1
-
Weight Route Predicate
使用权重来路由相应请求, 以下表示有80%的请求会被路由到localhost:8201,20%会被路由到localhost:8202。
spring: cloud: gateway: routes: - id: weight_high uri: http://localhost:8201 predicates: - Weight=group1, 8 - id: weight_low uri: http://localhost:8202 predicates: - Weight=group1, 2
七、路由过滤Filter
路由过滤器可用于修改进入的HTTP请求和返回的HTTP响应,路由过滤器只能指定路由进行使用,路由过滤的触发是在进行路由转发之前进行。
Spring Cloud Gateway 内置了多种路由过滤器,他们都由GatewayFilter的工厂类来产生。
-
AddRequestParameter
给请求添加参数的过滤器。
spring: cloud: gateway: routes: - id: add_request_parameter_route uri: http://localhost:8201 filters: - AddRequestParameter=username, zhangsan predicates: - Method=GET
以上配置会对GET请求添加
username=zhangsan
的请求参数,通过curl工具使用以下命令进行测试。curl http://localhost:9201/user/getByUsername
相当于发起该请求:
curl http://localhost:8201/user/getByUsername?username=zhangsan
-
StripPrefix
对指定数量的路径前缀进行去除的过滤器 。
spring: cloud: gateway: routes: - id: strip_prefix_route uri: http://localhost:8201 predicates: - Path=/user-service/** filters: - StripPrefix=2
以上配置会把以
/user-service/
开头的请求的路径去除两位,通过curl工具使用以下命令进行测试。curl http://localhost:9201/user-service/a/user/1
相当于发起该请求:
curl http://localhost:8201/user/1
-
PrefixPath
与StripPrefix过滤器恰好相反,会对原有路径进行增加操作的过滤器 。
spring: cloud: gateway: routes: - id: prefix_path_route uri: http://localhost:8201 predicates: - Method=GET filters: - PrefixPath=/user
以上配置会对所有GET请求添加
/user
路径前缀,通过curl工具使用以下命令进行测试。curl http://localhost:9201/1
相当于发起该请求:
curl http://localhost:8201/user/1
-
Hystrix
Hystrix 过滤器允许你将断路器功能添加到网关路由中,使你的服务免受级联故障的影响,并提供服务降级处理。
-
添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
-
控制器类
@RestController public class FallbackController { @GetMapping("/fallback") public Object fallback() { Map<String,Object> result = new HashMap<>(); result.put("data",null); result.put("message","Get request fallback!"); result.put("code",500); return result; } }
-
添加配置
spring: cloud: gateway: routes: - id: hystrix_route uri: http://localhost:8201 predicates: - Method=GET filters: - name: Hystrix args: name: fallbackcmd fallbackUri: forward:/fallback
-
测试
关闭服务提供方,调用该地址进行测试:http://localhost:9201/user/1 ,发现已经返回了服务降级的处理信息。
-
-
RequestRateLimiter
RequestRateLimiter 过滤器可以用于限流,使用RateLimiter实现来确定是否允许当前请求继续进行,如果请求太大默认会返回HTTP 429-太多请求状态。
-
添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis-reactive</artifactId> </dependency>
-
添加配置
-
配置类
@Configuration public class RedisRateLimiterConfig { // 根据请求参数中的username进行限流 @Bean KeyResolver userKeyResolver() { return exchange -> Mono.just( exchange.getRequest().getQueryParams().getFirst("username") ); } // 根据访问IP进行限流 @Bean public KeyResolver ipKeyResolver() { return exchange -> Mono.just( exchange.getRequest().getRemoteAddress().getHostName() ); } }
-
配置文件
server: port: 9201 spring: redis: host: localhost password: 123456 port: 6379 cloud: gateway: routes: - id: requestratelimiter_route uri: http://localhost:8201 filters: - name: RequestRateLimiter args: # 每秒允许处理的请求数量 redis-rate-limiter.replenishRate: 1 # 每秒最大处理的请求数量 redis-rate-limiter.burstCapacity: 2 # 限流策略,对应策略的Bean key-resolver: "#{@ipKeyResolver}" predicates: - Method=GET logging: level: org.springframework.cloud.gateway: debug
-
-
测试
多次请求该地址:http://localhost:9201/user/1 ,会返回状态码为429的错误:
-
-
Retry
对路由请求进行重试的过滤器,可以根据路由请求返回的HTTP状态码来确定是否进行重试 。
spring: cloud: gateway: routes: - id: retry_route uri: http://localhost:8201 predicates: - Method=GET filters: - name: Retry args: # 需要进行重试的次数 retries: 1 # 返回哪个状态码需要进行重试,返回状态码为5XX进行重试 statuses: BAD_GATEWAY backoff: firstBackoff: 10ms maxBackoff: 50ms factor: 2 basedOnPreviousValue: false
当调用返回500时会进行重试,访问测试地址:http://localhost:9201/user/111,可以发现对应的服务方控制台报错2次,说明进行了一次重试。
-
自定义Filter
-
添加配置类
@Configuration public class CustomRouteFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { System.out.println("进入自定义过滤器"); if(exchange.getRequest().getQueryParams().get("user") != null){ System.out.println("验证成功!"); return chain.filter(exchange); }else{ System.out.println("验证失败!"); return exchange.getResponse().setComplete(); } } /** * 路由执行顺序(值越小越先执行) * @return */ @Override public int getOrder() { return -1; } }
-
测试使用
访问:http://localhost:8080/user/show 观察结果
访问:http://localhost:8080/user/show?user=xxx 观察结果
-
【源码地址】:GitHub