Spring Cloud Gateway 実践ガイド:基本設定から応用テクニックまで

Spring Cloud Gateway は Spring Boot と Project Reactor を基盤とした API ゲートウェイで、リクエストルーティング、フィルタリング、モニタリングなどの機能を提供します。以下では、Spring Boot 3 プロジェクトへの組み込み手順から高度な活用方法までを詳しく解説します。

1. 依存関係の追加

まず、pom.xml に Spring Cloud Gateway スターターを追加します。Spring Boot のバージョン管理は親 POM で行います。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.0</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <!-- その他の依存 -->
</dependencies>

2. application.yml の設定

ルーティングルールやその他の設定を application.yml に記述します。以下は基本構成です。

spring:
  application:
    name: my-gateway
  cloud:
    gateway:
      enabled: true
      discovery:
        locator:
          enabled: true
      routes:
        - id: user_service_route
          uri: https://user-api.example.com
          predicates:
            - Path=/api/users/**
          filters:
            - StripPrefix=1

3. メインクラス

起動クラスは通常の Spring Boot アプリケーションと同様に作成します。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyGatewayApplication.class, args);
    }
}

4. ルートとフィルターの設定

ルートの各要素を理解しましょう。

  • id:ルートを一意に識別する文字列
  • uri:転送先サービスのアドレス
  • predicates:リクエストのマッチ条件(パス、メソッド、ヘッダーなど)
  • filters:リクエスト/レスポンスを加工するフィルター

例:Path 述語でパスをマッチし、StripPrefix フィルターで最初のパス要素を除去します。

spring:
  cloud:
    gateway:
      routes:
        - id: product_route
          uri: http://product-service:8080
          predicates:
            - Path=/shop/products/**
          filters:
            - StripPrefix=2

5. 動的ルーティング(サービスディスカバリ連携)

Eureka や Consul などのサービスディスカバリと連携する場合、lb:// 形式の URI を使用して負荷分散を実現します。

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: order_route
          uri: lb://order-service
          predicates:
            - Path=/orders/**

6. 起動と動作確認

アプリケーションを起動し、設定したルートにリクエストを送信して動作を確認します。例えば http://gateway-host/api/users/123 が正しく内部サービスに転送されるかテストします。

7. 高度な機能の解説

7.1 フィルターチェーンと順序

フィルターは order プロパティ(数値が小さいほど優先)で実行順序を制御できます。複数のフィルターを組み合わせて複雑な処理を実現します。

7.2 代表的なフィルター

  • AddRequestHeader:リクエストヘッダーを追加
  • AddRequestParameter:クエリパラメータを追加
  • RewritePath:リクエストパスを書き換え
  • CircuitBreaker:サーキットブレーカーによるフォールバック
  • RequestRateLimiter:レート制限によるトラフィックコントロール

7.3 負荷分散とサービスディスカバリ

Spring Cloud Gateway は Spring Cloud LoadBalancer と統合されており、lb:// プレフィックスを使うことでクライアントサイドロードバランシングを実現します。

7.4 セキュリティ

Spring Security と組み合わせることで、OAuth2 や JWT による認証・認可をゲートウェイレベルで適用できます。

7.5 モニタリング

Spring Boot Actuator と連携し、/gateway/routes で現在のルート一覧を、/gateway/globalfilters でグローバルフィルターを確認できます。

7.6 パフォーマンスチューニング

WebFlux ベースの非同期処理により高スループットを実現。必要に応じてスレッドプールサイズやメモリ設定を調整することで、さらなるパフォーマンス向上が可能です。

7.7 カスタムフィルターとルート定義

Java コードで独自のフィルターやルートを定義する方法も用意されています。これにより、ビジネスロジックに合わせた柔軟なゲートウェイ設計が行えます。

タグ: Spring Cloud Gateway Spring Boot 3 API Gateway WebFlux マイクロサービス

6月3日 22:11 投稿