javascript
SpringCloud-Gateway网关
文章目錄
- 前言
- 一、Gateway是什么
- 1、概述
- 2、三大核心概念
- 3、工作原理
- 二、使用步驟
- 1、引入庫
- 2、application.yml
- 3、主啟動類
- 4、其他
- 5、總結
- 三、Gateway的Predicate
- 四、Gateway的Filter
- 1、概覽
- 2、自定義全局GlobalFilter
- 3、自定義全局Filter案例
前言
今天大致學了下SpringCloud中的getaway的內容
一、Gateway是什么
1、概述
Gateway旨在提供一種簡單而有效的方式來對API進行路由,以及提供一些強大的過濾器功能,例如:熔斷、限流、重試等。
Spring Cloud Gateway的目標:提供統一的路由方式且基于Filter鏈的方式提供了網關基本的功能,例如:安全,監控/指標,和限流。
2、三大核心概念
3、工作原理
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發出請求。如果網關處理程序映射確定請求與路由匹配,則會將其發送到網關 Web 處理程序。此處理程序通過特定于請求的篩選器鏈運行請求。篩選器除以虛線的原因是篩選器可以在發送代理請求之前和之后運行邏輯。執行所有“pre”篩選器邏輯。然后發出代理請求。發出代理請求后,將運行“post”篩選器邏輯。
二、使用步驟
1、引入庫
<!--gateway--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency>2、application.yml
server:port: 9527 spring:application:name: cloud-gateway #############################新增網關配置###########################cloud:gateway:discovery:locator:enabled: true #開啟從注冊中心動態創建路由的功能,利用微服務名進行路由routes:- id: payment_routh #payment_route #路由的ID,沒有固定規則但要求唯一,建議配合服務名#uri: http://localhost:8001 #匹配后提供服務的路由地址,固定路由uri: lb://cloud-payment-service #匹配后提供服務的路由地址,動態路由:根據注冊中心的服務名來動態訪問predicates:- Path=/payment/get/** #斷言,路徑相匹配的進行路由- id: payment_routh2 #payment_route #路由的ID,沒有固定規則但要求唯一,建議配合服務名#uri: http://localhost:8001 #匹配后提供服務的路由地址,固定路由uri: lb://cloud-payment-service #匹配后提供服務的路由地址,動態路由:根據注冊中心的服務名來動態訪問predicates:- Path=/payment/lb/** #斷言,路徑相匹配的進行路由#- Header=X-Request-Id, \d+ #斷言,要header,且為正數#- Cookie=username,sakanal #斷言,要包含cookie,且key=username,value=sakanal#如果路徑為/api/C,則路由到B;如果路徑為/api/A,則路由到A#但是如果AB的擺放順序發生變動,則兩個路徑都只會路由到B,先匹配的先路由#在路由規則的順序上,將精確的路由規則放置到模糊的路由規則的前面,#否則的話,精確的路由規則將不會被匹配到,類似于異常體系中try catch子句中異常的處理順序。#可以使用order準確指定路由順序- id: Auri: lb://Apredicates:- Path=/api/A/**- id: Buri: lb://Bpredicates:- Path=/api/**#如果路徑是/api/C,經過該路由會被過濾器改為/admin/C- id: Curi: lb://Cpredicates: - Path=/api/** filters:- RewritePath=/api/(?<segment>.*),/admin/$\{segment}#################################################################### eureka:instance:instance-id: cloud-gateway-serviceclient:register-with-eureka: truefetch-registry: trueservice-url:#單機模式(注冊中心)defaultZone: http://eureka7001.com:7001/eureka/3、主啟動類
@SpringBootApplication @EnableEurekaClient public class GatewayMain9527 {public static void main(String[] args) {SpringApplication.run(GatewayMain9527.class, args);} }4、其他
編寫配置類的方式來配置路由
@Configuration public class GatewayConfig {/*** 配置了一個id為route-name的路由規則* 當訪問地址為http://localhost:9527/guonei時會自動轉發地址http://news.baidu.com/guonei* @param routeLocatorBuilder* @return*/@Beanpublic RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder) {RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();routes.route("path_route_atguigu",r -> r.path("/guonei")//===>predicates: - Path=/guonei.uri("http://news.baidu.com/guonei"))//===>uri: http://news.baidu.com/guonei.build();return routes.build();} }5、總結
在使用gateway后,可以通過網關來決定(是否/如何/…)調用服務
不必暴露實際服務的接口或地址,而是暴露網關的接口。就像將所有服務套一層殼,可以一定程度上的保護服務
三、Gateway的Predicate
官方文檔
Spring Cloud Gateway matches routes as part of the Spring WebFlux HandlerMapping infrastructure.
Spring Cloud Gateway includes many built-in route predicate factories. All of these predicates match on different attributes of the HTTP request.
You can combine multiple route predicate factories with logical and statements.
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
The After Route Predicate Factory
– After=2017-01-20T17:42:47.789-07:00[America/Denver]
– 采用一個參數,即日期時間。此route predicate匹配在指定日期時間之后發生的請求。
The Before Route Predicate Factory
– Before=2017-01-20T17:42:47.789-07:00[America/Denver]
– 采用一個參數,即日期時間。此route predicate匹配在指定日期時間之前發生的請求。
The Between Route Predicate Factory
– Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
– 采用一個參數,即日期時間。此route predicate匹配在指定日期時間之間發生的請求。
The Cookie Route Predicate Factory
– Cookie=chocolate, ch.p
– 采用兩個參數,即 cookie 名稱和正則表達式。此route predicate匹配具有給定名稱且其值與正則表達式匹配的 Cookie
The Header Route Predicate Factory
– Header=X-Request-Id, \d+
– 采用兩個參數:標頭名稱和正則表達式。此route predicate與具有給定名稱的標頭匹配,其值與正則表達式匹配
The Host Route Predicate Factory
– Host=**.somehost.org,**.anotherhost.org
– 采用一個參數:主機名模式列表。該模式是作為分隔符的 Ant 樣式模式。此route predicate與與模式匹配的標頭匹配。
The Method Route Predicate Factory
– Method=GET,POST
– 采用一個或多個參數:要匹配的 HTTP 方法。
The Path Route Predicate Factory
– Path=/red/{segment},/blue/{segment}
– 采用兩個參數:Spring 模式列表和名為 的可選標志。
The Query Route Predicate Factory
– Query=green
– 采用兩個參數:必需參數和可選參數。
The RemoteAddr Route Predicate Factory
– RemoteAddr=192.168.1.1/24
– 采用 CIDR 表示法(IPv4 或 IPv6)字符串的列表(最小大小 1),例如(其中是 IP 地址,是子網掩碼)
The weight Route Predicate Factory
– Weight=group1, 2
– 采用兩個參數:組和權重。權重是按組計算的
四、Gateway的Filter
官方文檔
Route filters allow the modification of the incoming HTTP request or outgoing HTTP response in some manner. Route filters are scoped to a particular route. Spring Cloud Gateway includes many built-in GatewayFilter Factories.
1、概覽
路由過濾器可用于修改進入的HTTP請求和返回的HTTP響應,路由過濾器只能指定路由進行使用。Spring Cloud Gateway內置了多種路由過濾器,他們都由GatewayFilter的工廠類來產生。
- 生命周期
- pre
- post
- 種類
- GatewayFilter - 有31種
- GlobalFilter - 有10種
常用的GatewayFilter:AddRequestParameter GatewayFilter
2、自定義全局GlobalFilter
兩個主要接口介紹:
- GlobalFilter
- Ordered
能干什么:
- 全局日志記錄
- 統一網關鑒權
- …
3、自定義全局Filter案例
@Component @Slf4j public class MyLogGateWayFilter implements GlobalFilter,Ordered {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain){log.info("***********come in MyLogGateWayFilter: "+new Date());String uname = exchange.getRequest().getQueryParams().getFirst("uname");if(uname == null){log.info("*******用戶名為null,非法用戶,o(╥﹏╥)o");exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);return exchange.getResponse().setComplete();}return chain.filter(exchange);}@Overridepublic int getOrder(){return 0;} }總結
以上是生活随笔為你收集整理的SpringCloud-Gateway网关的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 除了Micrsoft Office和WP
- 下一篇: 检测是否是ie浏览器及ie版本号