上一代網關zuul 1.X:https://github.com/Netflix/zuul/wiki
當前網關gateway:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/
一、概述簡介
Gateway是在Spring生態系統只上構建的API網關服務,基於Spring 5,Spring Boot 2和Project Reactor等技術。Gateway旨在提供一種簡單而有效的方式來對API進行路由,以及提供一些強大的過濾功能,例如熔斷、限流、重試等。
SrpingCloud Gateway作為Spring Cloud生態系統中的網關,目標是替代Zuul,在Spring Cloud2.0以上版本中,Spring Cloud沒有對新版本的Zuul 2.0以上最新高性能版本進行集成,仍然還是使用Zuul 1.x非Reactor模式的老版本,而為了提供網關的性能,SpringCloud Gateway是基於WebFlux框架實現的,而webFlux框架底層使用了高性能的Reactor模式通信框架Netty。
SpringCloud Gateway的目標提供統一的路由方式且基於Filter鏈的方式提供了網關基本的功能,例如:安全、監控/指標、和限流。
Spring Cloud Gateway 使用的Webflux中的reactor-netty響應式編程組件,底層使用了Netty通訊框架。
SpringCloud Gateway的功能作用:反向代理、鑒權、流量控制、熔斷、日志監控。
1.1、微服務架構中網關的使用位置
1.2、有了Zuul了怎么又出來了gateway
一方面因為Zuul1.0已經進入了維護階段,而且Gateway是SpringCloud團隊研發的,值得信賴。而且很多功能Zuul都沒有用起來也非常的簡單便捷。Gateway是基於異步非阻塞模型上進行開發的,性能方面不需要擔心,雖然Netflix早就發布了最新的Zuul 2.x,但是Spring Cloud貌似沒有整合計划,而且Netflix相關組件都宣布進入維護期。多方面考慮Gateway是很理想的網關選擇。
SpringCloud Gateway具有如下特性:
-
- 動態路由:能夠匹配任何請求屬性;
- 可以對路由指定Predicate(斷言)和Filter(過來器);
- 集成Spring Cloud服務發現功能;
- 易於編寫的Predicate(斷言)和Filter(過濾器);
- 請求限流功能。
1.3、SpringCloud Gateway與Zuul的區別
在SpringCloud finchley正式版之前,SpringCloud推薦的網關是Netflix提供的Zuul;
-
-
-
Zuul 1.x基於Servlet2.5使用阻塞架構它不支持任何長連接(如 WebSocket)Zuul的設計模式和Nginx較像,每次I/O操作都是從工作線程中選擇一個執行。請求線程被阻塞到工作線程完成,但是差別是Nginx用C++實現,Zuul用Java實現,而JVM本身會有第一次加載較慢的情況,使得Zuul的性能相對較差。
-
Zuul 2.x理念更先進,想基於Netty非阻塞和支持長連接,但是Spring Cloud目前還沒有整合。Zuul 2.x的性能較Zuul 1.x有較大提示。在性能方面,根據官方提供的基准測試,Spring Cloud Gateway的RPS(每秒請求數)是Zuul 1.x的1.6倍。
-
SpringCloud Gateway建立在 Spring Framework 5,Project Reactor和Spring Boot 2.0之上,使用非阻塞API
-
SpringCloud Gateway還支持WebSocket,並且與Spring緊密集成擁有更好的開發體驗。
-
Zuul1.x模型;Srpingcloud中所集成的Zuul版本,采用的是Tomcat容器,使用的是傳統的Servlet IO處理模型。Servlet的生命周期
- 容器啟動時構造servlet對象並調用servlet的init()方法。
- 容器運行時接受請求,並為每個請求分配一個線程(一般從線程池中獲取空閑線程)然后調用Service().
- 容器關閉時調用servlet destory()銷毀servlet。
上述模式的缺點:
servlet是一個簡單的網絡IO模型,當請求進入Servlet 容器時,servlet容器就會為其綁定一個線程,在並發不高的場景下這種模型是適用的。但是一旦高並發(用Jemeter壓)線程數量就會上漲,而線程資源代價是昂貴的(上下文切換,內存消耗大)嚴重影響請求的處理時間。在一些簡單業務場景下,不希望為每一個request分配一個線程,只需要1個或者幾個線程就能應對極大並發的請求,這種業務場景下servlet模型沒有優勢。
所以Zuul 1.x是基於servlet只上的一個阻塞式處理模型,即spring實現了處理所有request請求的一個servlet(DispatcherServlet)並由該servlet阻塞式處理,所以 Springcloud Zuul無法擺脫servlet模式的弊端。
二、Gateway的
2.1、Route(路由)
路由是構建網關的基本模塊,它由ID,目標URI,一系列的斷言和過濾器組成,如果斷言為true則匹配該路由。
2.2、Predicate(斷言)
參考的是java8的java.util.function.Predicate開發人員可以匹配HTTP請求中的所有內容(例如請求頭或請求參數),如果請求與斷言相匹配則進行路由。
2.3、Filter(過濾)
指的是Spring框架中GatewayFilter的實例,使用過濾器,可以在請求被路由前或者之后對請求進行修改。
2.4、總體
Web請求,通過一些匹配條件,定位到真正的服務節點,並在這個轉發過程的前后,進行一些精細化控制。
predicate就是我們的匹配條件,而filter,就可以理解為一個無所不能的攔截器,有了這兩個元素,再加上目標url,就可以實現一個具體的路由了。
三、Gateway工作流程
- 客戶端向SpringCloud Gateway發出請求。然后Gateway Handler Mapping中找到與請求相匹配的理由,將其發送到Gateway Web Handler。
- Handler在通過指定的過濾器鏈來將請求發送到我們實際的服務執行業務邏輯,然后返回。過濾器之間用虛線分開是因為過濾器可能會在發送代理請求之前(“pre”)或之后(“post”)執行業務邏輯。
- Filter在“pre”類型的過濾器可以做參數校驗,權限校驗,流量監控、日志輸出、協議轉換等,在“post”類型的過濾器中可以做響應內容,響應頭的修改,日志的輸出,流量監控等有着非常重要的作用。
- 核心邏輯:路由轉發+執行過濾器鏈。
四、案例
Gateway網關路由有兩種配置方式
- 在配置文件yml中配置
- 代碼中注入RouteLocator的Bean
4.1、yml方式配置路由
需求:之前cloud-provider-payment8001的controller的訪問地址 get/lb;我們目前不想暴露8001端口,希望在8001外面套一層9527;9527網關做路由映射。
- 新建Spring Boot 的Module名稱:cloud-gateway-gateway9527
- pom.xml添加如下依賴
<dependencies> <!--新增gateway--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</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>
- 編寫application.yml
server: port: 9527 spring: application: name: cloud-gateway cloud: gateway: routes: #配路由 - id: payment_routh #路由的ID, #沒有固定規則但要求唯一,建議配合服務名 uri: http://localhost:8001 #匹配后提供服務的路由地址 predicates: - Path=/payment/get/** #斷言,路徑相匹配的進行路由 - id: payment_routh2 uri: http://localhost:8001 predicates: - Path=/payment/lb/** #斷言,路徑相匹配的進行路由 eureka: instance: hostname: cloud-gateway-service client: service-url: register-with-eureka: true fetch-registry: true defaultZone: http://eureka7001.com:7001/eureka
- 主啟動類
@SpringBootApplication @EnableDiscoveryClient public class GateWayMain9527 { public static void main(String[] args) { SpringApplication.run( GateWayMain9527.class,args); } }
- 測試
啟動7001 + 啟動8001(cloud-provider-payment8001)+啟動9527網關
添加網關前訪問 :http://localhost:8001/payment/get/31
添加網關后訪問:http://localhost:9527/payment/get/31
4.2、代碼注入配置路由
代碼中注入RouteLocator的Bean
/** * 配置一個id為 path_route_jdy的路由規則,當訪問地址http://localhost:9527/u/jdy1022/時 * 自動轉發到地址https://home.cnblogs.com/u/jdy1022/ * */ @Configuration public class gatewayConfig { @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){ RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes(); routes.route("path_route_jdy", r -> r.path("/u/jdy1022/") .uri("https://home.cnblogs.com/u/jdy1022/")).build(); return routes.build(); } }
五、通過微服務名動態路由
默認情況下Gateway會根據注冊中心的服務列表,以注冊中心上微服務名為路徑創建動態路由進行轉發,從而實現動態路由的功能。
- 需要注意的是uri的協議為lb,表示啟用Gateway的負載均衡功能。
- lb://serviceName是spring cloud gateway在微服務中自動為我們創建的負載均衡uri
server: port: 9527 spring: application: name: cloud-gateway cloud: gateway: discovery: locator: enabled: true # 開啟從注冊中心動態創建路由的功能,利用微服務名進行路由 routes: - id: payment_routh #路由的ID,沒有固定規則但要求唯一,建議配合服務名 # uri: http://localhost:8001 #匹配后提供服務的路由地址 uri: lb://cloud-payment-service #匹配后提供服務的路由地址 predicates: - Path=/payment/get/** #斷言,路徑相匹配的進行路由 - id: payment_routh2 # uri: http://localhost:8001 uri: lb://cloud-payment-service predicates: - Path=/payment/lb/** #斷言,路徑相匹配的進行路由 eureka: instance: hostname: cloud-gateway-service client: service-url: register-with-eureka: true fetch-registry: true defaultZone: http://eureka7001.com:7001/eureka
一個eureka7001+兩個服務提供者8001/8002
http://localhost:9527/payment/lb
8001/8002兩個端口切換
六、Predicate的使用
6.1、Route Predicate Factories這個是什么?
Spring Cloud Gateway將路由作為Spring WebFluxHandlerMapping
基礎架構的一部分進行匹配。Spring Cloud Gateway包括許多內置的路由 predicate 工廠。所有這些 predicate 都與HTTP請求的不同屬性匹配。您可以將多個路由 predicate 工廠與邏輯and
語句結合使用。
6.2、常用的Route Predicate
(1)、After Route Predicate
該Predicate匹配在指定日期時間之后發生的請求。以下示例配置了路由后謂詞:
spring: cloud: gateway: routes: - id: after_route uri: https://example.org predicates: - After=2017-01-20T17:42:47.789-07:00[America/Denver]
//獲取上面的時間串 ZonedDateTime zonedDateTime = ZonedDateTime.now(); System.out.println(zonedDateTime); //2021-05-10T20:28:03.324+08:00[Asia/Shanghai]
(2)、Before Route Predicate
該Predicate匹配在指定日期時間之前發生的請求。以下示例配置了路由后謂詞:
spring: cloud: gateway: routes: - id: before_route uri: https://example.org predicates: - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
(3)、Between Route Predicate
該Predicate匹配在指定日期時間之間發生的請求。以下示例配置了路由后謂詞:
spring: cloud: gateway: routes: - id: between_route uri: https://example.org predicates: - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
(4)、Cookie Route Predicate
spring: cloud: gateway: routes: - id: cookie_route uri: https://example.org predicates: - Cookie=username,jdy
Cookie Route Predicate需要兩個參數,一個是Coookie name,一個是正則表達式,路由規則會通過獲取對應的 Cookie name值和正則表達式去匹配,如果匹配上就會執行路由,如果沒有匹配上則不執行。
-
不帶cookies訪問curl http://localhost:9527/payment/lb
-
帶上cookies訪問curl http://localhost:9527/payment/lb --cookie "username=jdy"
(5)、Header Route Predicate
兩個參數,一個屬性名稱和一個正則表達式,屬性值和正則表達式匹配則執行。
spring: cloud: gateway: routes: - id: header_route uri: https://example.org predicates: - Header=X-Request-Id, \d+ # 請求頭中要有X-Request-Id屬性並且值為整數的正則表達式
curl http://localhost:9527/payment/lb -H "X-Request-Id:123"
(6)、After Route Predicate
Host Route Predicate接受一組參數,一組匹配的域名列表,這個模板是一個ant分隔的模板,用.號作為分隔符。它通過參數中的主機地址作為匹配規則。
spring: cloud: gateway: routes: - id: host_route uri: https://example.org predicates: - Host=**.jdy.com
curl http://localhost:9527/payment/lb -H "Host:jdy.com"
(7)、After Route Predicate
spring: cloud: gateway: routes: - id: method_route uri: https://example.org predicates: - Method=GET,POST
curl http://localhost:9527/payment/lb -H "Method:get"
或者curl http://localhost:9527/payment/lb ,默認是get請求
(8)、After Route Predicate
只有訪問指定路徑,才進行路由
spring: cloud: gateway: routes: - id: host_route uri: https://example.org predicates: - Path=/payment/lb/**
curl http://localhost:9527/payment/lb
(9)、After Route Predicate
spring: cloud: gateway: routes: - id: query_route uri: https://example.org predicates: - Query=username, \d+ #要有參數名稱並且是正整數才能路由
curl http://localhost:9527/payment/lb?username=2
說白了,Predicate就是為了實現一組匹配規則,讓請求過來找到對應的Route進行處理。
七、Filter的使用
7.1、是什么
路由過濾器可用於修改進入的HTTP請求和返回的HTTP響應,路由過濾器只能指定路由進行使用。Spring Cloud Gateway 內置了多種路由過濾器,都是由GatewayFilter的工廠類來產生。
7.2、Spring Cloud Gateway的Filter
-
生命周期兩個
-
pre 在業務邏輯之前
-
post 在業務邏輯之后
-
-
種類
-
GatewayFilter單一
-
GlobalFilter全局
-
7.3、常用的GatewayFilter
server: port: 9527 spring: application: name: cloud-gateway cloud: gateway: discovery: locator: enabled: true # 開啟從注冊中心動態創建路由的功能,利用微服務名進行路由 routes: - id: payment_routh #路由的ID,沒有固定規則但要求唯一,建議配合服務名 # uri: http://localhost:8001 #匹配后提供服務的路由地址 uri: lb://cloud-payment-service #匹配后提供服務的路由地址 predicates: - Path=/payment/get/** #斷言,路徑相匹配的進行路由 - id: payment_routh2 # uri: http://localhost:8001 uri: lb://cloud-payment-service filter: - AddRequestParameter=X-Request-Id,1024 #過濾器工廠會在匹配的請求頭加上一對請求頭,名稱為X-Request-Id值為1024 predicates: - Path=/payment/lb/** #斷言,路徑相匹配的進行路由 #- Cookie=username,jdy #- Header=X-Request-Id, \d+ # 請求頭中要有X-Request-Id屬性並且值為整數的正則表達式 # - Host=**.jdy.com # - Method=GET # - Path=/payment/lb/** - Query=username, \d+ #要有參數名稱並且是正整數才能路由 eureka: instance: hostname: cloud-gateway-service client: service-url: register-with-eureka: true fetch-registry: true defaultZone: http://eureka7001.com:7001/eureka
7.4、自定義過濾器
自定義全局GlobalFilter,兩個主要接口介紹impiemerts GlobalFilter ,Ordered
能干嘛
-
全局日志記錄
-
統一網關鑒權
@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 uname = exchange.getRequest().getQueryParams().getFirst("username"); if(StringUtils.isEmpty(username)){ log.info("*****用戶名為Null 非法用戶,(┬_┬)"); exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);//給一個回應 return exchange.getResponse().setComplete(); } return chain.filter(exchange); } @Override public int getOrder() { return 0; } }