Spring Cloud Gateway

SpringCloud Gateway是Spring Cloud的一個子項目,該項目是基於Spring5.0、SpringBoot2.0和Project Reactor等技術開發的網關,它旨在爲微服務架構提供一種簡單有效的統一的API路由管理。spring

Spring Cloud Gateway具備以下特性:api

  • 基於Spring Frameworke 五、Project Reactor和Spring Boot2.0構建cookie

  • 可以匹配任何請求屬性上的路由;架構

  • 能夠對路由指定Predicate和Filter;app

  • 集成了Hystrix的斷路器功能;ide

  • 集成了Spring Cloud服務發現功能;微服務

  • 易於編寫Predicate和Filter;學習

  • 請求限流功能;ui

  • 支持路徑重寫;url

簡答介紹一些上邊的幾個術語:

  1. Filter:和zuul的過濾器在概念上相似,可使用它攔截和修改請求,而且對上游的響應進行二次處理。過濾器爲org.springframework.cloud.gateway.filter.GatewayFilter類的實例。

  2. Route:網關配置的基本組成模塊,和Zuul的路由配置模塊相似。一個Route模塊由一個ID,一個目標URI,一組斷言和一組過濾器定義。若是斷言爲真,則路由匹配,目標的URI會被訪問。

  3. Predicate:這是一個Java8的Predicate,可使用它來匹配來自HTTP請求的任何內容,例如headers或參數。斷言的輸入類型是一個ServerWebExchange。

須要在pom.xml中添加的依賴

<dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-starter-gateway</artifactId></dependency>


Spring Cloud Gateway有兩種不一樣的配置路由的方式:

方式一: 使用yml配置

server:  port: 8080spring:  application:    name: api-gateway  cloud:    gateway:      routes:        -id: api-gateway#路由的id          uri: ${service-url.user-service}/user/{id}#匹配後路由的地址          predicates:#斷言,路徑相匹配的進行路由            -Path=/user/{id}

方式二:  使用Java Bean配置

@configurationpublic class GatewayConfig{    @Bean    public RouteLocator customRouteLocator(RouteLocatorBuilder builder){        return builder.routes()                .route("path_route2", r -> r.path("/user/getByUsername")                     .uri("http://localhost:8201/user/getByUsername"))                   .build();    }}

Spring Cloud Gateway的工做方式:

客戶端向Spring Cloud Gateway發出請求。若是網關處理程序映射肯定請求與路由匹配,則將其發送到網關Web處理程序。該處理程序經過特定於請求的過濾器鏈來運行請求。篩選器由虛線分隔的緣由是,篩選器能夠在發送代理請求以前和以後運行邏輯。全部「前置」過濾器邏輯均被執行。而後發出代理請求。發出代理請求後,將運行「後」過濾器邏輯。

Route Predicate的使用

Spring Cloud Gateway將路由做爲Spring WebFlux HandlerMapping基礎架構的一部分進行匹配,Spring Cloud Gateway有不少內置的Route Predicate工廠,全部這些Predicate都與http請求的不一樣屬性匹配。多個Route Predicate工廠能夠組合使用。

The After Route Predicate Factory

After Route Predicate有一個參數,一個datetime,該Route匹配在指定日期時間以後發生的請求。

spring:   cloud:    gateway:      routes:      - id: after_route        uri: https://example.org        predicates:        - After=2020-03-20T15:00:00+08:00[Asia/Shanghai]

The Before  Route  Predicate Factory

匹配指定時間以前的請求

spring:  cloud:    gateway:      routes:      - id: before_route        uri: https://example.org        predicates:        - Before=2020-03-20T15:00:00+08:00[Asia/Shanghai]

The Between Route Predicate Factory

匹配指定時間區間內的請求

spring:  cloud:    gateway:      routes:        - id: between_route          uri: ${service-url.user-service}          predicates:            - Between=2020-03-20T15:00:00+08:00[Asia/Shanghai], 2020-03-20T16:00:00+08:00[Asia/Shanghai]

The Cookie Route Predicate Factory

匹配帶有指定cookie的請求

spring:  cloud:    gateway:      routes:      - id: cookie_route        uri: ${service-url.user-service}        predicates:        - Cookie=username,guli #只有cookie爲username=guli的請求能夠匹配

The Header Route Predicate Factory

匹配帶有指定請求頭的請求

spring:  cloud:    gateway:      routes:      - id: header_route        uri: ${service-url.user-service}        predicates:        - Header=X-Request-Id, \d+

The Host Route Predicate Factory

匹配帶有指定Host的請求

spring:  cloud:    gateway:      routes:      - id: host_route        uri: ${service-url.user-service}        predicates:        - Host=**.guli.com #只有請求頭帶有Host:www.guli.com的請求能夠匹配該路由

The Method Route Predicate Factory

匹配指定方法的請求

spring:  cloud:    gateway:      routes:      - id: method_route        uri: ${service-url.user-service}        predicates:        - Method=GET,POST #該路由匹配GET、POST請求

The Path Route Predicate Factory

匹配指定路徑的請求

spring:  cloud:    gateway:      routes:      - id: method_route        uri: ${service-url.user-service}        predicates:          - Path=/user/{id} #只能匹配/user/id路徑的請求

The Query Route Predicate Factory

匹配帶有指定查詢參數的請求

spring:  cloud:    gateway:      routes:      - id: query_route        uri: ${service-url.user-service}/user/getByUsername        predicates:        - Query=username #只有發送帶有username查詢參數的請求能夠匹配

The RemoteAddr Route Predicate Factory

匹配指定遠程地址發送的請求

spring:  cloud:    gateway:      routes:      - id: remoteaddr_route        uri: ${service-url.user-service}        predicates:        - RemoteAddr=192.168.1.1/24 #這個遠程地址根據實際狀況填寫

The Weight Route Predicate Factory

使用權重來路由相應的請求

spring:  cloud:    gateway:      routes:      - id: weight_high        uri: http://localhost:8001        predicates:        - Weight=group1, 8 #80%的請求路由到localhost:8001      - id: weight_low        uri: http://localhost:8002        predicates:        - Weight=group1, 2 #20%的請求路由到localhost:8002

GatewayFilter工廠的使用

路由過濾器容許以某種方式修改傳入的HTTP請求或傳出的HTTP響應。路由過濾器適用於特定路由。Spring Cloud Gateway包括許多內置的GatewayFilter工廠。下面介紹幾種經常使用的路由過濾器的用法:

The AddRequestHander GatewayFilter Factory

spring:  cloud:    gateway:      routes:      - id: add_request_header_route        uri: https:localhost:8001        predicates:        - Path=/red/{segment}        filters:        - AddRequestHeader=X-Request-Red, Blue-{segment}

The AddRequestParameter GatewayFilter Factory

這是給請求添加參數的過濾器

spring:  cloud:    gateway:      routes:        - id: add_request_parameter_route          uri: http://localhost:8001          filters:            - AddRequestParameter=username, guli          predicates:            - Method=GET

這個配置就是給Get請求添加username=guli的請求參數,發送http://localhost:8001/user/getByUsername,就至關於發送了http://localhost:8001/user/getByUsername?username=guli

The Hystrix GatewayFilter Factory

Hystrix過濾器容許將斷路器功能添加在網關路由中,使服務免於受到級聯故障的影響,而且提供服務降級功能。

須要在項目中引入Hystrix的相關依賴:

<dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>

服務降級的fallback:

@RestControllerpublic class fallBack(){    @GetMapping("/fallback")    public Object fallback(){       Map<String,Object> result = new HashMap<>();        result.put("data",null);        result.put("message","Request fallback!");        result.put("code",500);        return result;    }}

添加相關配置:

spring:  cloud:    gateway:      routes:        - id: hystrix_route          uri: http://localhost:8001          predicates:            - Method=GET          filters:            - name: Hystrix              args:                name: fallbackcmd                fallbackUri: forward:/fallback

The stripPrefix Gateway Factory

對指定數量的路由前綴進行去除的過濾器、

spring:  cloud:    gateway:      routes:      - id: nameRoot        uri: https://localhost:8001        predicates:        - Path=/user-service/**        filters:        - StripPrefix=2 #對/user-service開頭的請求的路徑去除兩位

The  PrefixPath GatewayFilter Factory

對原有路徑進行增長操做

spring:  cloud:    gateway:      routes:      - id: prefixpath_route        uri: https://localhost:8001        filters:        - PrefixPath=/mypath #對全部請求加上/mypath的路徑前綴

The Retry GatewayFilter Factory

根據路由請求返回的HTTP狀態碼來肯定是否進行重試。

spring:  cloud:    gateway:      routes:      - id: retry_test        uri: http://localhost:8001        predicates:        - Method=GET        filters:        - name: Retry          args:            retries: 3 #須要進行重試的次數            statuses: BAD_GATEWAY #返回哪一個狀態碼時進行重試            backoff:              firstBackoff: 10ms              maxBackoff: 50ms              factor: 2              basedOnPreviousValue: false

其餘還有不少過濾器官網都有介紹,能夠學習

相關文章
相關標籤/搜索