文中涉及到了一些模塊代碼沒有給出,我一並上傳到github了,可以整個項目clone下來進行調試。
地址:https://github.com/stronglxp/springcloud-test
1、GateWay是什么
1.1 概念
Cloud全家桶中有個很重要的組件就是網關,在1.x版本中都是采用的Zuul網關。但在2.x版本中,zuul的升級一直跳票,SpringCloud最后自己研發了一個網關替代Zuul。
Gateway是在Spring生態系統之上構建的API網關服務,基於Spring 5,Spring Boot 2和Project Reactor等技術。
Gateway旨在提供一種簡單而有效的方式來對API進行路由,以及提供一些強大的過濾器功能,例如:熔斷、限流、重試等。
SpringCloud Gateway是Spring Cloud的一個全新項目,基於Spring 5.0+Spring Boot 2.0和Project Reactor等技術開發的網關,它旨在為微服務架構提供—種簡單有效的統一的API路由管理方式。
SpringCloud Gateway作為Spring Cloud 生態系統中的網關,目標是替代Zuul,在Spring Cloud 2.0以上版本中,沒有對新版本的Zul 2.0以上最新高性能版本進行集成,仍然還是使用的Zuul 1.x非Reactor模式的老版本。而為了提升網關的性能,SpringCloud Gateway是基於WebFlux框架實現的,而WebFlux框架底層則使用了高性能的Reactor模式通信框架Netty。
Spring Cloud Gateway的目標提供統一的路由方式且基於 Filter鏈的方式提供了網關基本的功能,例如:安全,監控/指標,和限流。
1.2 作用
- 方向代理
- 鑒權
- 流量控制
- 熔斷
- 日志監控
- …
1.3 微服務架構中網關的位置
2、GateWay非阻塞異步模型
2.1 為什么選擇Gateway?
netflix不太靠譜,zuul2.0一直跳票,遲遲不發布。
- 一方面因為Zuul1.0已經進入了維護階段,而且Gateway是SpringCloud團隊研發的,是親兒子產品,值得信賴。而且很多功能Zuul都沒有用起來也非常的簡單便捷。
- Gateway是基於異步非阻塞模型上進行開發的,性能方面不需要擔心。雖然Netflix早就發布了最新的Zuul 2.x,但Spring Cloud貌似沒有整合計划。而且Netflix相關組件都宣布進入維護期;不知前景如何?
- 多方面綜合考慮Gateway是很理想的網關選擇。
SpringCloud Gateway具有如下特性
- 基於Spring Framework 5,Project Reactor和Spring Boot 2.0進行構建;
- 動態路由:能夠匹配任何請求屬性;
- 可以對路由指定Predicate (斷言)和Filter(過濾器);
- 集成Hystrix的斷路器功能;
- 集成Spring Cloud 服務發現功能;
- 易於編寫的Predicate (斷言)和Filter (過濾器);
- 請求限流功能;
- 支持路徑重寫。
SpringCloud Gateway與Zuul的區別
- 在SpringCloud Finchley正式版之前,Spring Cloud推薦的網關是Netflix提供的Zuul。
- Zuul 1.x,是一個基於阻塞I/O的API Gateway。
- Zuul 1.x基於Servlet 2.5使用阻塞架構它不支持任何長連接(如WebSocket)Zuul的設計模式和Nginx較像,每次I/О操作都是從工作線程中選擇一個執行,請求線程被阻塞到工作線程完成,但是差別是Nginx用C++實現,Zuul用Java實現,而JVM本身會有第-次加載較慢的情況,使得Zuul的性能相對較差。
- Zuul 2.x理念更先進,想基於Netty非阻塞和支持長連接,但SpringCloud目前還沒有整合。Zuul .x的性能較Zuul 1.x有較大提升。在性能方面,根據官方提供的基准測試,Spring Cloud Gateway的RPS(每秒請求數)是Zuul的1.6倍。
- Spring Cloud Gateway建立在Spring Framework 5、Project Reactor和Spring Boot2之上,使用非阻塞API。
- Spring Cloud Gateway還支持WebSocket,並且與Spring緊密集成擁有更好的開發體驗
2.2 Zuul1.x模型
Springcloud中所集成的Zuul版本,采用的是Tomcat容器,使用的是傳統的Serviet IO處理模型。
Servlet的生命周期?servlet由servlet container進行生命周期管理。
- container啟動時構造servlet對象並調用servlet init()進行初始化;
- container運行時接受請求,並為每個請求分配一個線程(一般從線程池中獲取空閑線程)然后調用service);
- container關閉時調用servlet destory()銷毀servlet。
上述模式的缺點:
Servlet是一個簡單的網絡IO模型,當請求進入Servlet container時,Servlet container就會為其綁定一個線程,在並發不高的場景下這種模型是適用的。但是一旦高並發(如抽風用Jmeter壓),線程數量就會上漲,而線程資源代價是昂貴的(上線文切換,內存消耗大)嚴重影響請求的處理時間。在一些簡單業務場景下,不希望為每個request分配一個線程,只需要1個或幾個線程就能應對極大並發的請求,這種業務場景下servlet模型沒有優勢。
所以Zuul 1.X是基於servlet之上的一個阻塞式處理模型,即Spring實現了處理所有request請求的一個servlet (DispatcherServlet)並由該servlet阻塞式處理處理。所以SpringCloud Zuul無法擺脫servlet模型的弊端。
2.3 GateWay模型
WebFlux是什么?官方文檔
傳統的Web框架,比如說: Struts2,SpringMVC等都是基於Servlet APl與Servlet容器基礎之上運行的。
但是在Servlet3.1之后有了異步非阻塞的支持。而WebFlux是一個典型非阻塞異步的框架,它的核心是基於Reactor的相關API實現的。相對於傳統的web框架來說,它可以運行在諸如Netty,Undertow及支持Servlet3.1的容器上。非阻塞式+函數式編程(Spring 5必須讓你使用Java 8)。
Spring WebFlux是Spring 5.0 引入的新的響應式框架,區別於Spring MVC,它不需要依賴Servlet APl,它是完全異步非阻塞的,並且基於Reactor來實現響應式流規范。
Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spring Webflux. It does not work in a traditional Servlet Container or when built as a WAR.
3、GateWay工作流程
3.1 三大核心概念
- Route(路由) - 路由是構建網關的基本模塊,它由ID,目標URI,一系列的斷言和過濾器組成,如斷言為true則匹配該路由;
- Predicate(斷言) - 參考的是Java8的java.util.function.Predicate,開發人員可以匹配HTTP請求中的所有內容(例如請求頭或請求參數),如果請求與斷言相匹配則進行路由;
- Filter(過濾) - 指的是Spring框架中GatewayFilter的實例,使用過濾器,可以在請求被路由前或者之后對請求進行修改。
web請求,通過一些匹配條件,定位到真正的服務節點。並在這個轉發過程的前后,進行一些精細化控制。
predicate就是我們的匹配條件;而fliter,就可以理解為一個無所不能的攔截器。有了這兩個元素,再加上目標uri,就可以實現一個具體的路由了。
3.2 GateWay工作流程
Clients make requests to Spring Cloud Gateway. If the Gateway Handler Mapping determines that a request matches a route, it is sent to the Gateway Web Handler. This handler runs the request through a filter chain that is specific to the request. The reason the filters are divided by the dotted line is that filters can run logic both before and after the proxy request is sent. All “pre” filter logic is executed. Then the proxy request is made. After the proxy request is made, the “post” filter logic is run.
客戶端向Spring Cloud Gateway發出請求。然后在Gateway Handler Mapping 中找到與請求相匹配的路由,將其發送到GatewayWeb Handler。
Handler再通過指定的過濾器鏈來將請求發送到我們實際的服務執行業務邏輯,然后返回。
過濾器之間用虛線分開是因為過濾器可能會在發送代理請求之前(“pre”)或之后(“post")執行業務邏輯。
Filter在“pre”類型的過濾器可以做參數校驗、權限校驗、流量監控、日志輸出、協議轉換等,在“post”類型的過濾器中可以做響應內容、響應頭的修改,日志的輸出,流量監控等有着非常重要的作用。
核心邏輯:路由轉發 + 執行過濾器鏈。
4、GateWay模塊搭建
創建新module:cloud-gateway
pom.xml文件如下
<?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>com.codeliu</groupId>
<artifactId>springcloud-test</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>cloud-gateway</artifactId>
<dependencies>
<!--引入cloud-api-common模塊-->
<dependency>
<groupId>com.codeliu</groupId>
<artifactId>cloud-api-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.yml文件如下,注冊到eureka服務器
server:
port: 9527
spring:
application:
name: cloud-gateway
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:9001/eureka
啟動類如下
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class CloudGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(CloudGatewayApplication.class, args);
}
}
在provider模塊中,我們有一個接口如下
可以通過配置網關訪問該接口
spring:
application:
name: cloud-gateway
# 網關配置
cloud:
gateway:
routes:
- id: provider-payment-route1 # 路由的id,沒有固定規則但要求唯一,建議配合服務名
uri: http://localhost:8001 # 匹配后提供服務的路由地址
predicates:
- Path=/payment/** # 斷言,路徑相匹配的路由
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:9001/eureka
啟動Eureka服務器,啟動provider服務,然后啟動gateway服務,通過provider訪問該接口和通過gateway訪問該接口返回的結果一致。
5、GateWay配置路由的兩種方式
(1)通過yml文件配置,上一章就是這樣搞的。
(2)代碼中注入RouteLocator的Bean
RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
.maxTrustedIndex(1);
...
.route("direct-route",
r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
.uri("https://downstream1")
.route("proxied-route",
r -> r.remoteAddr(resolver, "10.10.1.1", "10.10.1.1/24")
.uri("https://downstream2")
)
我們可以自己寫一個訪問百度新聞網
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 配置路由有兩種方式:1、通過配置文件。2、通過配置類
* 這里通過配置類配置路由
*/
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customerRouteLocator(RouteLocatorBuilder routeLocatorBuilder) {
RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
// 第一個參數是路由的唯一id
// http://localhost:9527/guonei => http://news.baidu.com/guonei
routes.route("path_route_baidu",
r -> r.path("/guonei")
.uri("http://news.baidu.com/guonei")).build();
return routes.build();
}
}
瀏覽器輸入http://localhost:9527/guonei,返回http://news.baidu.com/guonei相同的頁面。
6、GateWay配置動態路由
默認情況下Gateway會根據注冊中心注冊的服務列表,以注冊中心上微服務名為路徑創建動態路由進行轉發,從而實現動態路由的功能(不寫死一個地址)。
修改GateWay模塊的yml文件
server:
port: 9527
spring:
application:
name: cloud-gateway
# 網關配置
cloud:
gateway:
discovery:
locator:
enabled: true # 開啟從注冊中心動態創建路由的功能,利用微服務名進行路由
routes:
- id: provider-payment-route1 # 路由的id,沒有固定規則但要求唯一,建議配合服務名
# uri: http://localhost:8001 # 匹配后提供服務的路由地址
uri: lb://provider-payment # 需要注意的是uri的協議為lb,表示啟用Gateway的負載均衡功能。lb://serviceName是spring cloud gateway在微服務中自動為我們創建的負載均衡uri。
predicates:
- Path=/payment/** # 斷言,路徑相匹配的路由
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:9001/eureka
啟動Eureka服務器,啟動兩個provider服務,啟動GateWay服務,重復訪問http://localhost:9527/payment/1,會輪詢訪問兩個provider服務的接口。
7、GateWay內置的Predicate
Spring Cloud Gateway將路由匹配作為Spring WebFlux HandlerMapping基礎架構的一部分。
Spring Cloud Gateway包括許多內置的Route Predicate工廠。所有這些Predicate都與HTTP請求的不同屬性匹配。多個RoutePredicate工廠可以進行組合。
Spring Cloud Gateway創建Route 對象時,使用RoutePredicateFactory 創建 Predicate對象,Predicate 對象可以賦值給Route。Spring Cloud Gateway包含許多內置的Route Predicate Factories。
所有這些謂詞都匹配HTTP請求的不同屬性。多種謂詞工廠可以組合,並通過邏輯and。
常用的Route Predicate Factory
(1)The After Route Predicate Factory
(2)The Before Route Predicate Factory
(3)The Between Route Predicate Factory
(4)The Cookie Route Predicate Factory
(5)The Header Route Predicate Factory
(6)The Host Route Predicate Factory
(7)The Method Route Predicate Factory
(8)The Path Route Predicate Factory
(9)The Query Route Predicate Factory
(10)The RemoteAddr Route Predicate Factory
(11)The weight Route Predicate Factory
可以嘗試在yml中配置一些predicate
server:
port: 9527
spring:
application:
name: cloud-gateway
# 網關配置
cloud:
gateway:
discovery:
locator:
enabled: true # 開啟從注冊中心動態創建路由的功能,利用微服務名進行路由
routes:
- id: provider-payment-route1 # 路由的id,沒有固定規則但要求唯一,建議配合服務名
# uri: http://localhost:8001 # 匹配后提供服務的路由地址
uri: lb://provider-payment # 需要注意的是uri的協議為lb,表示啟用Gateway的負載均衡功能。lb://serviceName是spring cloud gateway在微服務中自動為我們創建的負載均衡uri。
predicates:
- Path=/payment/** # 斷言,路徑相匹配的路由
# gateway內置的路由斷言:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
- id: after-route
uri: https://example.org
predicates:
# 對於同一個path,從上到下匹配,匹配成功后,后面的規則就不生效了
- Path=/example/**
# 這個時間后才生效
- After=2021-07-08T10:25:20.760+08:00[Asia/Shanghai]
- id: between-route
uri: https://example.org
predicates:
- Path=/example/**
- Between=2021-07-08T10:25:20.760+08:00[Asia/Shanghai], 2021-07-09T10:25:20.760+08:00[Asia/Shanghai]
- id: cookie-route
uri: https://example.org
predicates:
- Path=/example/**
- Cookie=chocolate, ch.p
- id: header-route
uri: https://example.org
predicates:
- Path=/example/**
- Header=X-Request-Id, \d+
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:9001/eureka
可以使用ZonedDateTime
生成上面這種格式的時間
// 生成gateway內置路由斷言工廠需要的時間戳格式 2021-07-05T10:25:20.760+08:00[Asia/Shanghai]
ZonedDateTime zbj = ZonedDateTime.now();
System.out.println(zbj);
上面我們加了4個內置的斷言,分別是After、Between、Cookie、Header,源uri是: https://example.org,匹配的uri是:/example/**
通過下面的請求進行測試
# 該命令相當於發get請求,且沒帶cookie
curl http://localhost:9527/example
# 帶cookie的
curl http://localhost:9527/example --cookie "chocolate=chip"
# 帶指定請求頭的參數的CURL命令
curl http://localhost:9527/example -H "X-Request-Id:123"
測試發現:對於同一個path,從上往下匹配規則,匹配上了就不會往下走了。
總結:predicate就是為了實現一組匹配規則,讓請求過來找到對應的Route進行處理。
8、GateWay的Filter
路由過濾器可用於修改進入的HTTP請求和返回的HTTP響應,路由過濾器只能指定路由進行使用。Spring Cloud Gateway內置了多種路由過濾器,他們都由GatewayFilter的工廠類來產生。
Spring Cloud Gateway的Filter:
- 生命周期:
- pre
- post
- 種類(具體看官方文檔):
- GatewayFilter - 有31種
- GlobalFilter - 有10種
如果我們要自定義一個全局GlobalFilter,需要實現GlobalFilter, Ordered接口。
比如我們實現一個Filter,所有通過該網關進行請求都需要帶上特定的字符串才行
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Date;
/**
* 這里自定義一個全局filter,實現 GlobalFilter 和 Ordered接口,所有的請求訪問都要先經過這個全局 filter驗證
*/
@Component
@Slf4j
public class MyLogGatewayFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("come in MyLogGatewayFilter: " + new Date());
String name = exchange.getRequest().getQueryParams().getFirst("name");
if (StringUtils.isBlank(name)) {
log.info("非法用戶!");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
// 繼續下一個filter
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
在上面的filter中我們規定所有請求過來都需要帶上name字段並且值不能為空。
訪問:http://localhost:9527/payment/1,后台打印【非法用戶!】,訪問:http://localhost:9527/payment/1?name=a,返回結果。