微服務網關 —— SpringCloud Gateway

Gateway 簡介

Spring Cloud Gateway 基於 Spring 5、Spring Boot 2 和 Project Reactor 等技術,是在 Spring 生態系統之上構建的 API 網關服務,Gateway 旨在提供一種簡單而有效的方式來對 API 進行路由以及提供一些強大的過濾器功能,例如熔斷、限流、重試等

Spring Cloud Gateway 具有如下特性:

  • 基於 Spring Framework 5、Project Reactor 以及 Spring Boot 2.0 進行構建
  • 能夠匹配任何請求屬性
  • 可以對路由指定 Predicate(斷言)和 Filter(過濾器)
  • 集成 Hystrix 的斷路器功能
  • 集成 Spring Cloud 服務發現功能
  • 易於編寫的 Predicate 和 Filter
  • 請求限流功能
  • 路徑重寫

Gateway 快速入門

創建項目,引入依賴

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

在配置文件 application.yml 添加如下配置

server:
  port: 9201 # 指定運行端口

spring:
  application:
    name: gateway-service # 指定服務名稱
  cloud:
    gateway:
      routes:
        - id: path_route  # 路由ID
          uri: http://localhost:8201/user/getUser  # 匹配後路由地址
          predicates: # 斷言,路徑相匹配的路由
            - Path=/user/getUser

也可以按如下配置

@Configuration
public class GatewayConfig {

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

Gateway 路由工廠

Spring Cloud Gateway 包括許多內置的路由斷言工廠,所有這些斷言都與 HTTP 請求的不同屬性匹配,多個路由斷言工廠可以進行組合

1. After Route Predicate Factory

在指定時間之後的請求會匹配該路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - After=2017-01-20T17:42:47.789-07:00[America/Denver]

2. Before Route Predicate Factory

在指定時間之前的請求會匹配該路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Before=2017-01-20T17:42:47.789-07:00[America/Denver]

3. Between Route Predicate Factory

在指定時間區間內的請求會匹配該路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]

帶有指定 Cookie 的請求會匹配該路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Cookie=milk, yili # cookie爲milk=yili

5. Header Route Predicate Factory

帶有指定請求頭的請求會匹配該路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Header=X-Request-Id, 1	# 請求頭爲X-Request-Id=1

6. Host Route Predicate Factory

帶有指定 Host 的請求會匹配該路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Host=**.somehost.org	# 請求頭爲Host:www.somehost.org的請求可以匹配該路由

7. Method Route Predicate Factory

發送指定方法的請求會匹配該路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Method=GET,POST

8. Path Route Predicate Factory

發送指定路徑的請求會匹配該路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Path=/red/(segment],/blue/(segment) # /red/1或/blue/1路徑請求可以匹配該路由

9. Query Route Predicate Factory

帶指定查詢參數的請求可以匹配該路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Query=green # 帶green=l查詢參數的請求可以匹配該路由

10. RemoteAddr Route Predicate Factory

從指定遠程地址發起的請求可以匹配該路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - RemoteAddr=192.168.1.1/24 # 從192.168.1.1發起請求可以匹配該路由

11. Weight Route Predicate Factory

使用權重來路由相應請求,以下代碼表示有 80% 的請求會被路由到 weighthigh.org,20% 會被路由到 weightlow.org

spring:
  cloud:
    gateway:
      routes:
        - id: weight-high
          uri: http://weighthigh.org
          predicates:
            - Weight=group1, 8
        - id: weight-low
          uri: http://weightlow.org
          predicates:
            - Weight=group1, 2

可以使用 metadata 爲每個 route 增加附加屬性

spring:
  cloud:
    gateway:
      routes:
        - id: route-with-metadata
          uri: http://example.org
          metadata:
          	optionName: "OptionValue"
          	compositeObject:
          		name: "value"
          	iAmNumber: 1

可以從 exchange 獲取所有元數據屬性:

Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
route.getMetadata();
route.getMetadata (someKey);

Gateway 過濾器工廠

路由過濾器可用於修改進入的 HTTP 請求和返回的 HTTP 響應,Spring Cloud Gateway 內置了多種路由過濾器,由 GatewayFilter 的工廠類產生

1. AddRequestParameter GatewayFilter

AddRequestParameter GatewayFilter 是給請求添加參數的過濾器·

spring:
  cloud:
    gateway:
      routes:
        - id: add_request_parameter_route
          uri: http://example.org
          filters:
          	- AddRequestParameter=username, tom	# 對GET請求添加usemame=tom的請求參數
          predicates:
            - Method=GET

2. StripPrefixPath GatewayFilter

PrefixPath GatewayFilter 是對指定數量的路徑前緩進行去除的過濾器

spring:
  cloud:
    gateway:
      routes:
        - id: strip_prefix_route
          uri: http://example.org
          filters:
          	# 把以/user-service/開頭的請求的路徑去除兩位
          	# 相當於http://1ocalhost:9201/user-service/a/user/1
          	# 轉換成http://localhost:8080/user/1
          	- StripPrefix=2 
          predicates:
            - Path=/user-service/**

3. PrefixPath GatewayFilter

與 StripPrefix 過濾器恰好相反,PrefixPath GatewayFilter 會對原有路徑進行增加操作

spring:
  cloud:
    gateway:
      routes:
        - id: prefix_prefix_route
          uri: http://example.org
          filters:
          	# 對所有GET請求添加/user路徑前綴
          	# 相當於http://1ocalhost:9201/get
          	# 轉換成http://localhost:8080/user/get
          	- PrefixPath=/user
          predicates:
            - Method-GET

Gateway 全局過濾器

GlobalFilter 全局過濾器與普通的過濾器 GatewayFilter 具有相同的接口定義,只不過 GlobalFilter 會作用於所有路由

發起請求時,Filtering Web Handler 處理器會添加所有 GlobalFilter 實例和匹配的 GatewayFilter 實例到過濾器鏈中,過濾器鏈會使用 @Ordered 註解所指定的順序進行排序,數值越小越靠前執行,默認 GatewayFilter 設置的 order 值爲 1,如果 GatewayFilter 和 GlovalFilter 設置的 order 值一樣,優先執行 GatewayFilter

@Component
public class CustomGlobalFilter implements GlobalFilter, ordered {
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("custom global filter");
        return chain.filter(exchange);
    }
    
    @Override
    public int getOrder() {
        return -1;
    }
}

Gateway 跨域

Gateway 是支持 CORS 的配置,可以通過不同的 URL 規則匹配不同的 CORS 策略,例如:

spring:
  cloud:
    gateway:
    	globalcors:
            corsConfiqurations:
                '[/**]':
                    allowedOrigins: "https://docs.spring.io"
                    allowedMethods:
                        - GET

在上面的示例中,對於所有 GET 請求,將允許來自 docs.spring.io 的 CORS 請求

Gateway 還提供更爲詳細的配置

spring:
  cloud:
    gateway:
    	globalcors:
            cors-confiqurations:
                '[/**]':
                	# 允許攜帶認證信息
                	allow-credentials: true
                	# 允許跨城的源(網站城名/ip),設置*爲全部
                    allowed-origins: 
                    - "http://localhost:13009"
                    - "http://localhost:13010"
                    # 允許跨城請求裏的head字段,設置*爲全部
                    allowed-headers: "*"
                    # 允許跨城的method,默認爲GET和OPTIONS,設置*爲全部
                    allowed-methods: 
                    - OPTIONS
                    - GET
                    - POST
                    # 跨域允許的有效期
                    max-age: 3600
                    # 允許response的head信息
                    # 默認僅允許如下6個:
                    # Cache-Control
                    # Content-Language
                    # Content-Type
                    # Expires
                    # Last-Modified
                    # Praqma
                    # exposed-headers:

HTTP 超時配置

1. 全局超時

spring:
  cloud:
    gateway:
    	httpclient:
    		connect-timeout: 1000 # 連接超時配置,單位爲毫秒
    		response-timeout: 5s # 響應超時,單位爲 java.time.Duration

2. 每個路由配置

spring:
  cloud:
    gateway:
      routes:
        - id: per_route_timeouts
          uri: http://example.org
          predicates:
            - Path=/user-service/**
          metadata:
          	response-timeout: 200 # 響應超時,單位爲毫秒
          	connect-timeout: 200 # 連接超時配置,單位爲毫秒

TLS/SSL 設置

在 Web 服務應用中,爲了數據的傳輸安全,會使用安全證書以及 TLS/SSL 加密,Gateway 可以通過遵循常規的 Spring 服務器配置來偵聽 HTTPS 上的請求

server:
	ssl:
		# 啓用ssl
		enabled: true
		# 啓用證書
		key-alias: scg
		# 證書密碼
		key-store-password: scg1234
		# 證書地址
		key-store: classpath:scg-keystore.pl2
		# 證書類型
		key-store-type: PKCS12

可以使用以下配置爲 Gateway 配置一組可信任的已知證書

spring:
  cloud:
    gateway:
    	httpclient:
    		ssl:
    			trustedX509Certificates:
                - certl.pem
                - cert2.pem
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章