Gateway 網(wǎng)關路由、斷言、過濾
點擊上方“程序員大白”,選擇“星標”公眾號
重磅干貨,第一時間送達

0x01: Gateway 簡介
是什么?
Spring Cloud 全家桶中有個很重要的組件:網(wǎng)關。在 1.x 版本中使用的是 Zuul 網(wǎng)關,但是到了 2.x,由于Zuul的升級不斷跳票,Spring Cloud 自己研發(fā)了一套網(wǎng)關組件:Spring Cloud Gateway。
Spring Cloud Gateway基于 Spring Boot 2.x,Spring WebFlux 和 Project Reactor 構建,使用了 Webflux 中的 reactor-netty 響應式編程組件,底層使用了 Netty 通訊框架。
詳見:官網(wǎng)
能干嘛?
反向代理、鑒權、流量控制、熔斷、日志監(jiān)控......
網(wǎng)關在微服務架構中的位置

0x02:Gateway 的三大概念
Route(路由):路由是構建網(wǎng)關的基本模塊,它由 ID、目標 URI、一系列的斷言和過濾器組成,如果斷言為 true 則匹配該路由
Predicate(斷言):參考的是 Java8 中的 java.util.function.Predicate。開發(fā)人員可以匹配 HTTP 請求中的所有內(nèi)容(例如請求頭或請求參數(shù)),如果請求與斷言相匹配則進行路由
Filter(過濾):指的是 Spring 框架中 GatewayFilter 的實例,使用過濾器,可以在請求被路由之前或之后對請求進行修改

0x03:工作流程

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 發(fā)出請求。如果網(wǎng)關處理程序映射確定請求與路由匹配,則將其發(fā)送到網(wǎng)關 Web 處理程序。該處理程序通過特定于請求的過濾器鏈來運行請求。 篩選器由虛線分隔的原因是,篩選器可以在發(fā)送代理請求之前和之后運行邏輯。所有 “前置“ 過濾器邏輯均被執(zhí)行,然后發(fā)出代理請求,發(fā)出代理請求后,將運行“ 后置 ”過濾器邏輯。
總結:路由轉發(fā) + 執(zhí)行過濾器鏈
0x04:兩種配置方式
配置文件方式
以訪問「百度新聞網(wǎng)」為例,添加如下配置
server:
port: 9527
spring:
application:
name: cloud-gateway9527
cloud:
gateway:
routes:
- id: news # 路由id
uri: http://news.baidu.com # 真實調(diào)用地址
predicates:
- Path=/guonei # 斷言,符合規(guī)則進行路由
瀏覽器雖然輸入 localhost:9527/guonei,卻會轉發(fā)到指定的地址

編碼方式
新增配置文件
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("news2", r -> r.path("/guoji").uri("http://news.baidu.com"))
.build();
}
效果:

0x05:動態(tài)路由
開啟后,默認情況下 Gateway 會根據(jù)注冊中心注冊的服務列表,以注冊中心上微服務名為路徑創(chuàng)建動態(tài)路由進行轉發(fā),從而實現(xiàn)動態(tài)路由的功能
spring:
cloud:
gateway:
discovery:
locator:
enabled: true #開啟從注冊中心動態(tài)創(chuàng)建路由的功能,利用微服務名進行路由
routes:
- id: payment_routh1
#uri: http://localhost:8001 #靜態(tài),寫死了地址,只能調(diào)用一個服務
uri: lb://CLOUD-PAYMENT-SERVICE #動態(tài),lb://微服務名
predicates:
- Path=/payment/get/**
- id: payment_routh2
#uri: http://localhost:8001
uri: lb://CLOUD-PAYMENT-SERVICE
predicates:
- Path=/payment/lb/**
0x06:Predicate 的使用
時間相關配置
After:在指定時間之后進行路由
Before:在指定時間之前進行路由
Between:在指定時間之間進行路由
predicates:
- Path=/payment/lb/**
#- After=2020-04-25T16:30:58.215+08:00[Asia/Shanghai]
#- Before=2020-04-25T16:40:58.215+08:00[Asia/Shanghai]
- Between=2020-04-25T16:35:58.215+08:00[Asia/Shanghai],2020-04-25T16:40:58.215+08:00[Asia/Shanghai]上述配置的時間格式可以通過以下代碼得到
@Test
public void test(){
ZonedDateTime now = ZonedDateTime.now();
System.out.println(now);
}
請求相關配置
Cookie
配置說明:【Cookie=cookie名, cookie值的正則表達式規(guī)則】
predicates:
- Path=/payment/lb/**
- Cookie=id, [0-9使用 curl 工具模擬攜帶 cookie 發(fā)送請求

Header
配置說明:【Header=header名, header值的正則表達式規(guī)則】
predicates:
- Path=/payment/lb/**
- Header=h, [a-h]

Host
配置說明:【Host=主機名(可配置多個,也可以使用通配符)】
predicates:
- Path=/payment/lb/**
- Host=**.a.com,**.b.cn

Method
配置說明:【Method=請求類型】
predicates:
- Path=/payment/lb/**
- Method=GET

Path
配置說明:【Path=請求路徑】
predicates:
- Path=/payment/lb/**

Query
配置說明:【Query=參數(shù)名,參數(shù)值】
predicates:
- Path=/payment/lb/**
- Query=name, zhangsan

詳見:官網(wǎng)
0x07:Filter 的使用
生命周期:pre、post
種類:GatewayFilter、GlobalFilter
GatewayFilter 在官方文檔有幾十種!詳細配置可參考 官網(wǎng),這里主要介紹自定義全局過濾器。
@Component
@Slf4j
public class MyGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String username = exchange.getRequest().getQueryParams().getFirst("username");
//用戶名為空時,給出錯誤響應
if (username == null) {
log.info("用戶名為空,非法登錄");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}


source:https://www.cnblogs.com/songjilong/p/12774265.html推薦閱讀
國產(chǎn)小眾瀏覽器因屏蔽視頻廣告,被索賠100萬(后續(xù))
年輕人“不講武德”:因看黃片上癮,把網(wǎng)站和786名女主播起訴了
關于程序員大白
程序員大白是一群哈工大,東北大學,西湖大學和上海交通大學的碩士博士運營維護的號,大家樂于分享高質(zhì)量文章,喜歡總結知識,歡迎關注[程序員大白],大家一起學習進步!

