マイクロサービスゲートウェイ——SpringCloudゲートウェイ

ゲートウェイの概要

Spring Cloud Gateway は、Spring 5、Spring Boot 2、Project Reactor などのテクノロジーに基づいています。Spring エコシステム上に構築された API ゲートウェイ サービスです。ゲートウェイは、API をルーティングするためのシンプルかつ効果的な方法を提供し、いくつかの強力なフィルター機能を提供することを目的としています。サーキットブレーカー、電流制限、再試行など。

Spring Cloud Gateway には次の機能があります。

  • Spring Framework 5、Project Reactor、Spring Boot 2.0 に基づいて構築
  • 任意のリクエスト属性に一致可能
  • ルートに対して述語とフィルターを指定可能
  • Hystrix の集積回路ブレーカー機能
  • Spring Cloudサービスディスカバリ機能を統合
  • 述語とフィルタの記述が簡単
  • リクエスト電流制限機能
  • パスの書き換え

ゲートウェイのクイックスタート

プロジェクトを作成して依存関係を導入する

<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();
    }
}

Nacos 登録センターを統合し、負荷分散用に複数のインスタンスを構成する場合は、構成ファイル application.yml を次のように構成します。

spring:
  cloud:
    gateway:
      routes:
        - id: service-01
          uri: lb://service-01	# service-01是在nacos注册的服务名,lb://表示启用负载均衡
          predicates:
            - Path=/service-01/**
        - id: service-02
          uri: lb://service-02
          predicates:
            - Path=/service-02/**

ゲートウェイルーティングファクトリー

Spring Cloud Gateway には、HTTP リクエストのさまざまな属性に一致する多くの組み込みルーティング アサーション ファクトリが含まれており、複数のルーティング アサーション ファクトリを組み合わせることができます。

1. ルート述語ファクトリーの後

指定された時間以降のリクエストはこのルートに一致します

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - After=2017-01-20T17:42:47.789-07:00[America/Denver]
2. ルート述語ファクトリーの前

指定された時間より前のリクエストはこのルートに一致します

spring:
  cloud:
    gateway:
      routes:
        - id: before_route
          uri: http://example.org
          predicates:
            - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
3. ルート述語ファクトリー間

指定された時間間隔内のリクエストはこのルートに一致します

spring:
  cloud:
    gateway:
      routes:
        - id: between_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]
4. Cookie ルート述語ファクトリー

指定された Cookie を含むリクエストはこのルートと一致します

spring:
  cloud:
    gateway:
      routes:
        - id: cookie_route
          uri: http://example.org
          predicates:
            - Cookie=milk, yili # cookie为milk=yili
5. ヘッダールート述語ファクトリー

指定されたリクエストヘッダーを持つリクエストはこのルートと一致します

spring:
  cloud:
    gateway:
      routes:
        - id: header_route
          uri: http://example.org
          predicates:
            - Header=X-Request-Id, 1	# 请求头为X-Request-Id=1
6. ホストルート述語ファクトリー

指定されたホストを持つリクエストはこのルートと一致します

spring:
  cloud:
    gateway:
      routes:
        - id: host_route
          uri: http://example.org
          predicates:
            - Host=**.somehost.org	# 请求头为Host:www.somehost.org的请求可以匹配该路由
7. メソッドルート述語ファクトリー

指定されたメソッドにリクエストを送信すると、このルートと一致します。

spring:
  cloud:
    gateway:
      routes:
        - id: method_route
          uri: http://example.org
          predicates:
            - Method=GET,POST
8. パス・ルート述語ファクトリー

指定されたパスにリクエストを送信すると、そのルートと一致します。

spring:
  cloud:
    gateway:
      routes:
        - id: path_route
          uri: http://example.org
          predicates:
            - Path=/red/{
    
    segment},/blue/{
    
    segment} # /red/1或/blue/1路径请求可以匹配该路由
9. クエリルート述語ファクトリー

指定されたクエリパラメータを持つリクエストはこのルートに一致します

spring:
  cloud:
    gateway:
      routes:
        - id: query_route
          uri: http://example.org
          predicates:
            - Query=green # 带green=l查询参数的请求可以匹配该路由
10. RemoteAddr ルート述語ファクトリー

指定されたリモート アドレスから開始されたリクエストは、このルートと一致する可能性があります

spring:
  cloud:
    gateway:
      routes:
        - id: remoteaddr_route
          uri: http://example.org
          predicates:
            - RemoteAddr=192.168.1.1/24 # 从192.168.1.1发起请求可以匹配该路由
11. ウェイトルート述語ファクトリー

対応するリクエストをルーティングするには、weight を使用します。次のコードは、リクエストの 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

メタデータを使用して、各ルートに追加の属性を追加できます。

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

すべてのメタデータ プロパティは交換から取得できます。

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

ゲートウェイフィルターファクトリー

ルーティング フィルターを使用して、受信 HTTP リクエストと返された HTTP レスポンスを変更できます。Spring Cloud Gateway には、GatewayFilter のファクトリ クラスによって生成されるさまざまな組み込みルーティング フィルターがあります。

1.AddRequestParameterゲートウェイフィルター

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 ゲートウェイフィルター

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 ゲートウェイフィルター

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

ゲートウェイ グローバル フィルター

GlobalFilter グローバル フィルターは、GlobalFilter がすべてのルートに作用することを除いて、通常のフィルター GatewayFilter と同じインターフェイス定義を持ちます。

リクエストが開始されると、フィルタリング Web ハンドラー プロセッサは、すべての GlobalFilter インスタンスと一致する GatewayFilter インスタンスをフィルタ チェーンに追加します。フィルタ チェーンは、アノテーションで指定された順序を使用して並べ替えられます。値が小さいほど、より早く実行されます@Ordered。 GatewayFilter のデフォルト設定 順序値は 1 です。GatewayFilter と GlovalFilter で設定した順序値が同じ場合、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;
    }
}

ゲートウェイクロスドメイン

ゲートウェイは CORS 構成をサポートしており、さまざまな URL ルールを通じてさまざまな CORS ポリシーを照合できます。次に例を示します。

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

上記の例では、docs.spring.io からの CORS リクエストがすべての GET リクエストに対して許可されます。

ゲートウェイはさらに詳細な設定も提供します

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 暗号化が使用され、ゲートウェイは通常の Spring サーバー構成に従って HTTPS 上のリクエストをリッスンできます。

server:
	ssl:
		# 启用ssl
		enabled: true
		# 启用证书
		key-alias: scg
		# 证书密码
		key-store-password: scg1234
		# 证书地址
		key-store: classpath:scg-keystore.pl2
		# 证书类型
		key-store-type: PKCS12

ゲートウェイは、次の構成を使用して、信頼できる既知の証明書のセットで構成できます。

spring:
  cloud:
    gateway:
    	httpclient:
    		ssl:
    			trustedX509Certificates:
                - certl.pem
                - cert2.pem

おすすめ

転載: blog.csdn.net/CSDN_handsome/article/details/132641009
おすすめ