Spring Cloud Gatewayの概要
Spring Cloud GatewayはSpring CloudエコシステムにおけるAPIゲートウェイで、非同期非ブロッキング処理を特徴としています。マイクロサービスアーキテクチャにおいて統一されたルーティング管理を提供し、Netflix Zuulの代替を目指しています。
主要コンポーネント
- Route(ルート): ルーティングの基本単位で、ID、宛先URI、述語セット、フィルターセットで構成されます
- Predicate(述語): Java 8のPredicateを基盤とし、HTTPリクエストの条件評価を行います
- Filter(フィルター): リクエストとレスポンスの加工処理を実行します
基本設定例
依存関係の定義
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
YAML設定ファイル
server:
port: 8080
spring:
cloud:
gateway:
routes:
- id: blog_redirect
uri: https://example.org
predicates:
- Path=/api/**
述語の種類と設定例
時間条件によるルーティング
routes:
- id: time_based_route
uri: https://service.example
predicates:
- After=2024-01-01T00:00:00+09:00[Asia/Tokyo]
# - Before=2024-12-31T23:59:59+09:00[Asia/Tokyo]
Cookie条件
routes:
- id: cookie_validation
uri: https://backend.example
predicates:
- Cookie=sessionId,.+
ヘッダー条件
routes:
- id: header_check
uri: https://api.example
predicates:
- Header=Authorization,Bearer.*
HTTPメソッド条件
routes:
- id: method_filter
uri: https://rest.example
predicates:
- Method=POST,PUT
パスパターン条件
routes:
- id: path_pattern
uri: https://resource.example
predicates:
- Path=/v1/users/{id}
クエリパラメータ条件
routes:
- id: query_param
uri: https://search.example
predicates:
- Query=category,books
複合条件の適用
routes:
- id: complex_conditions
uri: https://secure.example
predicates:
- Method=GET
- Path=/secure/**
- Header=X-API-Version,^v[0-9]+
- Query=token,.+
動作フロー
クライアントリクエストはGateway Handler Mappingで適切なルートにマッチングされ、Gateway Web Handlerを通じてフィルターチェーンを経由してバックエンドサービスに転送されます。フィルターはリクエスト転送前(pre)および転送後(post)に処理を実行します。