SpringBoot实战电商项目mall(20k+star)地址:github.com/macrozheng/…java
Spring Cloud Gateway 为 SpringBoot 应用提供了API网关支持,具备强大的智能路由与过滤器功能,本文将对其用法进行详细介绍。react
Gateway是在Spring生态系统之上构建的API网关服务,基于Spring 5,Spring Boot 2和 Project Reactor等技术。Gateway旨在提供一种简单而有效的方式来对API进行路由,以及提供一些强大的过滤器功能, 例如:熔断、限流、重试等。git
Spring Cloud Gateway 具备以下特性:github
这里咱们建立一个api-gateway模块来演示Gateway的经常使用功能。redis
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
复制代码
Gateway 提供了两种不一样的方式用于配置路由,一种是经过yml文件来配置,另外一种是经过Java Bean来配置,下面咱们分别介绍下。spring
server:
port: 9201
service-url:
user-service: http://localhost:8201
spring:
cloud:
gateway:
routes:
- id: path_route #路由的ID
uri: ${service-url.user-service}/user/{id} #匹配后路由地址
predicates: # 断言,路径相匹配的进行路由
- Path=/user/{id}
复制代码
启动eureka-server,user-service和api-gateway服务,并调用该地址测试:http://localhost:9201/user/1api
咱们发现该请求被路由到了user-service的该路径上:http://localhost:8201/user/1bash
/** * Created by macro on 2019/9/24. */
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("path_route2", r -> r.path("/user/getByUsername")
.uri("http://localhost:8201/user/getByUsername"))
.build();
}
}
复制代码
从新启动api-gateway服务,并调用该地址测试:http://localhost:9201/user/getByUsername?username=macrocookie
咱们发现该请求被路由到了user-service的该路径上:http://localhost:8201/user/getByUsername?username=macro架构
Spring Cloud Gateway将路由匹配做为Spring WebFlux HandlerMapping基础架构的一部分。 Spring Cloud Gateway包括许多内置的Route Predicate工厂。 全部这些Predicate都与HTTP请求的不一样属性匹配。 多个Route Predicate工厂能够进行组合,下面咱们来介绍下一些经常使用的Route Predicate。
注意:Predicate中提到的配置都在application-predicate.yml文件中进行修改,并用该配置启动api-gateway服务。
在指定时间以后的请求会匹配该路由。
spring:
cloud:
gateway:
routes:
- id: after_route
uri: ${service-url.user-service}
predicates:
- After=2019-09-24T16:30:00+08:00[Asia/Shanghai]
复制代码
在指定时间以前的请求会匹配该路由。
spring:
cloud:
gateway:
routes:
- id: before_route
uri: ${service-url.user-service}
predicates:
- Before=2019-09-24T16:30:00+08:00[Asia/Shanghai]
复制代码
在指定时间区间内的请求会匹配该路由。
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的请求会匹配该路由。
spring:
cloud:
gateway:
routes:
- id: cookie_route
uri: ${service-url.user-service}
predicates:
- Cookie=username,macro
复制代码
使用curl工具发送带有cookie为username=macro
的请求能够匹配该路由。
curl http://localhost:9201/user/1 --cookie "username=macro"
复制代码
带有指定请求头的请求会匹配该路由。
spring:
cloud:
gateway:
routes:
- id: header_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的请求会匹配该路由。
spring:
cloud:
gateway:
routes:
- id: host_route
uri: ${service-url.user-service}
predicates:
- Host=**.macrozheng.com
复制代码
使用curl工具发送带有请求头为Host:www.macrozheng.com
的请求能够匹配该路由。
curl http://localhost:9201/user/1 -H "Host:www.macrozheng.com"
复制代码
发送指定方法的请求会匹配该路由。
spring:
cloud:
gateway:
routes:
- id: method_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
复制代码
发送指定路径的请求会匹配该路由。
spring:
cloud:
gateway:
routes:
- id: path_route
uri: ${service-url.user-service}/user/{id}
predicates:
- Path=/user/{id}
复制代码
使用curl工具发送/user/1
路径请求能够匹配该路由。
curl http://localhost:9201/user/1
复制代码
使用curl工具发送/abc/1
路径请求没法匹配该路由。
curl http://localhost:9201/abc/1
复制代码
带指定查询参数的请求能够匹配该路由。
spring:
cloud:
gateway:
routes:
- id: query_route
uri: ${service-url.user-service}/user/getByUsername
predicates:
- Query=username
复制代码
使用curl工具发送带username=macro
查询参数的请求能够匹配该路由。
curl http://localhost:9201/user/getByUsername?username=macro
复制代码
使用curl工具发送带不带查询参数的请求没法匹配该路由。
curl http://localhost:9201/user/getByUsername
复制代码
从指定远程地址发起的请求能够匹配该路由。
spring:
cloud:
gateway:
routes:
- id: remoteaddr_route
uri: ${service-url.user-service}
predicates:
- RemoteAddr=192.168.1.1/24
复制代码
使用curl工具从192.168.1.1发起请求能够匹配该路由。
curl http://localhost:9201/user/1
复制代码
使用权重来路由相应请求,如下表示有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
复制代码
路由过滤器可用于修改进入的HTTP请求和返回的HTTP响应,路由过滤器只能指定路由进行使用。Spring Cloud Gateway 内置了多种路由过滤器,他们都由GatewayFilter的工厂类来产生,下面咱们介绍下经常使用路由过滤器的用法。
给请求添加参数的过滤器。
spring:
cloud:
gateway:
routes:
- id: add_request_parameter_route
uri: http://localhost:8201
filters:
- AddRequestParameter=username, macro
predicates:
- Method=GET
复制代码
以上配置会对GET请求添加username=macro
的请求参数,经过curl工具使用如下命令进行测试。
curl http://localhost:9201/user/getByUsername
复制代码
至关于发起该请求:
curl http://localhost:8201/user/getByUsername?username=macro
复制代码
对指定数量的路径前缀进行去除的过滤器。
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
复制代码
与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 过滤器容许你将断路器功能添加到网关路由中,使你的服务免受级联故障的影响,并提供服务降级处理。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
复制代码
/** * Created by macro on 2019/9/25. */
@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
复制代码
RequestRateLimiter 过滤器能够用于限流,使用RateLimiter实现来肯定是否容许当前请求继续进行,若是请求太大默认会返回HTTP 429-太多请求状态。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
复制代码
/** * Created by macro on 2019/9/25. */
@Configuration
public class RedisRateLimiterConfig {
@Bean
KeyResolver userKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("username"));
}
@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 #每秒最大处理的请求数量
key-resolver: "#{@ipKeyResolver}" #限流策略,对应策略的Bean
predicates:
- Method=GET
logging:
level:
org.springframework.cloud.gateway: debug
复制代码
对路由请求进行重试的过滤器,能够根据路由请求返回的HTTP状态码来肯定是否进行重试。
spring:
cloud:
gateway:
routes:
- id: retry_route
uri: http://localhost:8201
predicates:
- Method=GET
filters:
- name: Retry
args:
retries: 1 #须要进行重试的次数
statuses: BAD_GATEWAY #返回哪一个状态码须要进行重试,返回状态码为5XX进行重试
backoff:
firstBackoff: 10ms
maxBackoff: 50ms
factor: 2
basedOnPreviousValue: false
复制代码
当调用返回500时会进行重试,访问测试地址:http://localhost:9201/user/111
能够发现user-service控制台报错2次,说明进行了一次重试。
2019-10-27 14:08:53.435 ERROR 2280 --- [nio-8201-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
at com.macro.cloud.controller.UserController.getUser(UserController.java:34) ~[classes/:na]
复制代码
咱们上次讲到使用Zuul做为网关结合注册中心进行使用时,默认状况下Zuul会根据注册中心注册的服务列表,以服务名为路径建立动态路由,Gateway一样也实现了该功能。下面咱们演示下Gateway结合注册中心如何使用默认的动态路由和过滤器。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
复制代码
server:
port: 9201
spring:
application:
name: api-gateway
cloud:
gateway:
discovery:
locator:
enabled: true #开启从注册中心动态建立路由的功能
lower-case-service-id: true #使用小写服务名,默认是大写
eureka:
client:
service-url:
defaultZone: http://localhost:8001/eureka/
logging:
level:
org.springframework.cloud.gateway: debug
复制代码
在结合注册中心使用过滤器的时候,咱们须要注意的是uri的协议为
lb
,这样才能启用Gateway的负载均衡功能。
/user
路径并路由;server:
port: 9201
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
- id: prefixpath_route
uri: lb://user-service #此处须要使用lb协议
predicates:
- Method=GET
filters:
- PrefixPath=/user
discovery:
locator:
enabled: true
eureka:
client:
service-url:
defaultZone: http://localhost:8001/eureka/
logging:
level:
org.springframework.cloud.gateway: debug
复制代码
springcloud-learning
├── eureka-server -- eureka注册中心
├── user-service -- 提供User对象CRUD接口的服务
└── api-gateway -- gateway做为网关的测试服务
复制代码
mall项目全套学习教程连载中,关注公众号第一时间获取。