GateWay
一、GateWay是什麼
Cloud全家桶中有個很重要的組件就是網關,在1.x版本中都是採用的Zuul網關
但是在2.x版本中,zuul的升級一直跳票,SpringCloud最後自己研發了一個網關代替Zuul
那就是Springcloud Gateway一句話: gateway是原zuul 1.x版的替代
1.1 一句話形容Gateway
Springcloud Gateway使用的Webflux中的reactor-netty響應式編程組件,底層使用了Netty通訊框架
1.2 微服務架構中網關在那裏
二、有Zuul了怎麼又出來了gateway
2.1 我們爲什麼選擇Gateway
neflix不太靠譜,zuul2.0一直跳票,遲遲不發佈
2.2 SpringCloud Gateway具有如下特性
- 基於Spring Framework 5,Project Reactor 和 Spring Boot 2.0 進行構建
- 動態路由:能夠匹配任何請求屬性
- 可以對路由指定 Predicate (斷言)和 Filter(過濾器)
- 集成Hystrix的斷路器功能
- 集成Spring Cloud 服務發現功能
- 易於編寫的 Predicate(斷言)和Filter(過濾器)
- 請求限流功能
- 支持路徑重寫
2.3 SpringCloud Gateway 與 Zuul的區別
SpringCloud Finchley正式版之前,Spring Cloud 推薦的網關是Netflix提供的Zuul
- Zull 1.x 是一個基於阻塞 I/O 的API Gateway
- Zull 1.x 基於Sevlet 2.5 使用阻塞構架它不支持任何長連接(如 WebSocket) Zuul的設計模式和Nginx較像,每次I/O操作都是從工作線程中選擇一個執行,請求線程被阻塞到工作線程完成,但是差別是Nginx用C++實現,Zuul用Java實現,而JVM本身會有第一次加載較慢的情況,使得Zuul的性能相對較差
- Zuul 2.x 理念更先進,想基於Netty非阻塞和支持長連接,但SpringCloud目前還沒有整合。Zuul 2.x的性能較1.x又較大i生。在性能方面,根據官網提供的基準測試,Spring Cloud Gateway 的 RPS(每秒請求數)是zuul的1.6倍
- Spring Cloud Gateway建立在Spring Framework 5, Project Reactor 和 Spring Boot 2之上,使用非阻塞的API
- Spring Cloud Gateway還支持 WebSocket,並且與Spring緊密集成擁有更好的開發體驗。
三、Zuul 1.x 模型
Zuul 1.x 是基於servlet之上的一個阻塞式處理模型,即spring實現了處理所有request請求的一個servlet 並由該servlet阻塞式處理處理,所以Springcloud Zuul無法擺脫serverlet模型的弊端
四、Gateway模型
五、Gateway三大核心概念
5.1 Route 路由
路由是構建網關的基本模塊,它由ID,目標URI,一系列的斷言和過濾器組成,如果斷言爲true則匹配該路由
5.2 Predicate(斷言)
參考的是Java8的java.util.function.Predicate
開發人員可以匹配HTTP請求中的所有內容(例如請求頭或請求參數),如果請求與斷言相匹配則進行路由
5.3 Filter(過濾)
指的是Spring框架中GatewayFilter的實例,使用過濾器,可以在請求被路由器前或者之後對請求進行修改。
5.4 總體
Web請求,通過一系列匹配條件,定位到真正的服務節點。並在這個轉發過程的前後,進行一些精細化的控制
predicate就是我們的匹配條件
filter,可以理解爲一個無所不能的攔截器。有了這兩個元素在加上目標uri,就可以實現一個具體的路由了
六、Gateway的工作流程
6.1 官網總結
- 客戶端向Spring Cloud Gateway發出請求。然後在Gateway Handler Mapping 中找到與請求相匹配的路由,將其發送到Gateway Web Handler
- Handler 再通過指定的過濾器鏈來將請求發送到我們實際的服務執行業務邏輯,然後返回
- 過濾器之間用虛線分開是因爲過濾器可能會再發送代理請求之前(“pre”)或之後(“post")執行業務邏輯
- Filter在”pre"類型的過濾器可以做參數校驗,權限校驗,流量監控,日誌輸出,協議轉換等,在"post"類型的過濾器中可以做響應式內容,響應頭的修改,日誌的輸出,流量監控等有着非常重要的作用。
6.2 核心邏輯
路由轉發+執行過濾器鏈
七、 新建module cloud-gateway-gateway9527
7.1 pom
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cloud2020</artifactId>
<groupId>com.aiguigu.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-gateway-gateway9527</artifactId>
<dependencies>
<!--gateway-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--eureka client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--引入自定義的api通用包,可使用Payment支付Entity-->
<dependency>
<groupId>com.aiguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</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>
</project>
7.2 application.yml
server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
routes:
- id: payment_routh #payment_routh #路由的ID,沒有固定規則但要求唯一,簡易配合服務名
uri: http://localhost:8001 #匹配後提供服務的路由地址
predicates:
- Path=/payment/get/** #斷言,路徑相匹配的進行路由
- id: payment_routh2 #payment_routh #路由的ID,沒有固定規則但要求唯一,簡易配合服務名
uri: http://localhost:8001 #匹配後提供服務的路由地址
predicates:
- Path=/payment/lb/** #斷言,路徑相匹配的進行路由
eureka:
instance:
hostname: cloud-gateway-service
client:
fetch-registry: true
register-with-eureka: true
service-url:
#設置與Eureka Server交互的地址查詢服務和註冊服務都需要依賴這個地址
# defaultZone: http://eureka7002.com:7002/eureka/
# 單機版eureka
defaultZone: http://eureka7001.com:7001/eureka/
7.3 主啓動類
package com.atguigu.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class GatewayMain9527 {
public static void main(String[] args) {
SpringApplication.run(GatewayMain9527.class,args);
}
}
7.4 測試
已經註冊成功:
7.4 路由器的另外一種配置方法
這裏新建一個config
配置路由規則,代替yml配置
package com.atguigu.springcloud.config;
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;
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){
RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
routes.route("path_route_atguigu",
r -> r.path("/guonei").uri("http://news.baidu.com/guonei")).build();
return routes.build();
}
}
測試:
八、動態路由
8.1 修改yml
8.2 測試
九、Gateway常用的Preducate(斷言)
9.1 斷言的種類
請求要滿足斷言表達式爲true才能訪問,只要一個不符合就訪問不到服務
9.2 配置時間斷言
在當前時間之後才能訪問
時間格式複雜怎麼辦?這裏有生成當前時間的方法
import java.time.ZonedDateTime;
public class TimeBulider {
public static void main(String[] args) {
ZonedDateTime zonedDateTime=ZonedDateTime.now();
System.out.println(zonedDateTime);
}
}
測試,如果我將時間調至明天,再次訪問會出現找不到服務
可以看到這裏斷言還有After,Before和Between,方法都是大同小異
9.3 Cookie斷言
- Cookie Route Predicate需要兩個參數,一個是Cookie name ,一個是正則表達式
- 路由規則會通過獲取對應的Cookie name 值和正則表達式去匹配,如果匹配上就去執行路由,如果沒有匹配上則不執行
- 以上是配置的Cookie
- 下面我們用命令框的CURL去訪問,出現了負載均衡
9.4 Header斷言
- Header=X-Request-Id, \d+
#請求頭需要有X-Request-Id屬性名,值爲整數正則表達式
命令輸入:http://localhost:9527/payment/lb -H “X-Request-Id:1234”,負數就直接報錯
9.5 總結
所有斷言不一一舉例了,說白了Predicate就是爲了實現一組匹配規則,讓請求過來找到對應的Route進行處理
十、Gateway的filter
- 指的是Spring框架中GatewayFilter的實例,使用過濾器,可以請求被路由前或者之後對請求進行修改
- 路由過濾器可用於進入的HTTP 請求和返回的HTTP響應,路由過濾器只能指定路由進行使用
- Spring cloud Gateway內置了多種路由器,他們都由GatewayFile的工廠類來產生
- 常用的GatewayFilter有31種
- 全局的Filter有10種
10.1 自定義全局GlobalFilter
創建Gateway配置類
實現一個GlobalFilter
package com.atguigu.springcloud.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
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;
@Component
@Slf4j
@Order(0)
public class MyLogGateWayFilter implements GlobalFilter,Ordered{
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("***************Come in My LogGlobalFilter "+new Date());
String uname = exchange.getRequest().getQueryParams().getFirst("uname");
if(uname==null){
log.info("*******用戶名非法,請稍後再試!");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
// @Override 實現上面@Order(0)註解就可以不用實現接口
public int getOrder() {
return 0;
}
}
測試
注意:請求進來必須帶有uname的參數纔可以訪問,測試如下