はじめに
マイクロサービスアーキテクチャが一般的になる中で、APIゲートウェイの重要性が増しています。Springエコシステムを使っているなら、Spring Cloud Gatewayは非常に強力な選択肢です。
この記事では、Spring Cloud Gatewayの基本的な使い方を、初心者向けにわかりやすく解説します。
🌐 Spring Cloud Gatewayとは?
Spring Cloud Gatewayは、Spring公式が提供する非同期・ノンブロッキングなAPIゲートウェイです。以下のような機能を提供します:
- ルーティング(リクエストの振り分け)
- フィルター(認証、ロギング、ヘッダー操作など)
- 負荷分散(Spring Cloud LoadBalancerとの連携)
- Circuit Breaker(Resilience4jとの統合)
🛠️ 環境構築
必要なもの
- Java 17以上
- Spring Boot 3.x
- Maven または Gradle
pom.xml の依存関係(Mavenの場合)
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
最小構成のルーティング設定
application.yml
spring:
cloud:
gateway:
routes:
- id: sample_route
uri: https://httpbin.org/get
predicates:
- Path=/get
この設定では、/get にアクセスすると https://httpbin.org/get にリクエストが転送されます。
🧪 動作確認
アプリケーションを起動して、以下のURLにアクセスしてみましょう:
http://localhost:8080/get
httpbin.org からのレスポンスが返ってくれば成功です!
🖼️ Spring Cloud Gatewayの基本構成図
※図はクライアント → Gateway → バックエンドサービスの流れを示しています。
🔍 フィルターの追加例
filters:
- AddRequestHeader=X-Request-Example, GatewayDemo
このフィルターは、リクエストヘッダーに X-Request-Example: GatewayDemo を追加します。
📌 まとめ
Spring Cloud Gatewayは、シンプルな構成で強力なAPIゲートウェイを構築できるツールです。次回以降は、カスタムフィルターの作成や認証との連携など、より実践的な内容を紹介します。
