新しいSpring Cloud Gatewayを探る
1概要
この記事では、Spring 5、Spring Boot 2、Project Reactorをベースにした新しいAPIであるhttp://cloud.spring.io/spring-cloud-gateway/[Spring Cloud Gateway]プロジェクトの主な機能を探ります。 。
このツールは、単一のファサードの背後に複数のサービスを隠す方法として、マイクロサービスアプリケーションでよく使用されるすぐに使えるルーティングメカニズムを提供します。
Spring Cloud GatewayプロジェクトのないGatewayパターンの説明については、/spring-cloud-gateway-pattern[前の記事]のリンクを確認してください。
2ルーティングハンドラ
ルーティングリクエストに焦点を絞って、Spring Cloud GatewayはリクエストをGateway Handler Mappingに転送します。これは、特定のルートに一致するリクエストに対して何を行うべきかを決定します。
__RouteLocatorを使用してゲートウェイハンドラがルート設定を解決する方法の簡単な例から始めましょう。
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("r1", r -> r.host("** ** .baeldung.com")
.and()
.path("/baeldung")
.uri("http://baeldung.com"))
.route(r -> r.host("** ** .baeldung.com")
.and()
.path("/myOtherRouting")
.filters(f -> f.prefixPath("/myPrefix"))
.uri("http://othersite.com")
.id("myOtherID"))
.build();
}
このAPIの主な構成要素をどのように利用したかに注目してください。
-
Route –
ゲートウェイのプライマリAPI。それは与えられたによって定義されます
識別(ID)、宛先(URI)、および述語のセット
フィルター
**
Predicate –
Java 8の
Predicate –
はHTTPのマッチングに使われます
ヘッダ、メソッド、またはパラメータを使用したリクエスト
**
Filter –
標準のSpringの
WebFilter
3動的ルーティング
Zuul
のように、Spring Cloud Gatewayはリクエストをさまざまなサービスにルーティングする手段を提供します。
ルーティング設定は、純粋なJava(セクション2.1の例に示すように
RouteLocator
)を使用するか、プロパティ設定を使用して作成できます。
spring:
application:
name: gateway-service
cloud:
gateway:
routes:
- id: baeldung
uri: baeldung.com
- id: myOtherRouting
uri: localhost:9999
4ルーティングファクトリ
Spring Cloud GatewayはSpring WebFlux
HandlerMapping
インフラストラクチャを使用してルートを照合します。
それはまた多くの作り付けのルート述語工場を含みます。これらの述語はすべて、HTTP要求のさまざまな属性と一致します。複数のルート述語ファクトリは論理的な「and」を使って組み合わせることができます。
ルートマッチングは、プログラム的に、または異なるタイプのルート述語ファクトリを使用して構成プロパティファイルを介して適用できます。
4.1.
前
ルート述語工場
Before
ルート述語ファクトリは1つのパラメータを取ります。
spring:
cloud:
gateway:
routes:
- id: before__route
uri: http://baeldung.com
predicates:
- Before=2017-09-11T17:42:47.789-07:00[America/Alaska]----
Java構成は次のように表すことができます。
[source,java,gutter:,true]
----//..route definition
.route(r -> r.before(LocalDateTime.now().atZone(ZoneId.systemDefault()))
.id("before__route")
.uri("http://baeldung.com")
4.2. ルート述語工場間
Between
Route Predicate Factoryは、
datetime1、
、および
datetime2
の2つのパラメーターを取ります。この述部は、
datetime1
(これを含む)の後、および
datetime2
(これを含まない)の前に発生する要求と一致します。
datetime2
パラメーターは
datetime1
の後になければなりません。
spring:
cloud:
gateway:
routes:
- id: between__route
uri: http://baeldung.com
predicates:
- Between=2017-09-10T17:42:47.789-07:00[America/Alaska], 2017-09-11T17:42:47.789-07:00[America/Alaska]----
そしてJavaの設定は次のようになります。
[source,java,gutter:,true]
ZonedDateTime datetime1 = LocalDateTime.now().minusDays(1).atZone(ZoneId.systemDefault());
ZonedDateTime datetime2 = LocalDateTime.now().atZone(ZoneId.systemDefault())//..route definition
.route(r → r.between(datetime1, datetime2))
.id(“between__route”)
.uri(“http://baeldung.com”)
==== ** 4.3. __ヘッダー__ルート述語工場** __Header__ Route Predicate Factoryは、ヘッダー名と正規表現という2つのパラメーターを取ります。この述語は、正規表現に一致するヘッダーと一致します。 [source,javascript,gutter:,true]
Java構成は次のように表すことができます。 [source,java,gutter:,true] ----//..route definition .route(r -> r.header("X-Request-Id", "\\d+") .id("header__route") .uri("http://baeldung.com")
4.4.
ホスト
ルート述語係数
Host
Route Predicate Factoryは1つのパラメータ、ホスト名パターンを取ります。パターンは、区切り文字として「。」を使用したAntスタイルのパターンです。
この述語は
Host
ヘッダを与えられたパターンで照合します
spring:
cloud:
gateway:
routes:
- id: host__route
uri: http://baeldung.com
predicates:
- Host=** ** .baeldung.com
これがJava設定の代替手段です。
----//..route definition
.route(r -> r.host("** ** .baeldung.com")
.id("host__route")
.uri("http://baeldung.com")
----
4.5.
方法
ルート述語工場
Method
Route Predicate Factoryは1つのパラメータを取ります。照合するHTTPメソッドです。
spring:
cloud:
gateway:
routes:
- id: method__route
uri: http://baeldung.com
predicates:
- Method=GET
Java構成は次のように表すことができます。
----//..route definition
.route(r -> r.method("GET")
.id("method__route")
.uri("http://baeldung.com")
----
4.6.
Path
ルート述語ファクトリー
Path
ルート述語ファクトリは1つのパラメータを取ります:Spring
PathMatcher
パターン:
spring:
cloud:
gateway:
routes:
- id: path__route
uri: http://baeldung.com
predicates:
- Path=/articles/{articleId}
Javaの設定
----//..route definition
.route(r -> r.path("/articles/"+articleId)
.id("path__route")
.uri("http://baeldung.com")
----
4.7.
Query
ルート述部ファクトリー
Query
Route Predicate Factoryは2つのパラメータを取ります:必須のパラメータとオプションの正規表現です。
spring:
cloud:
gateway:
routes:
- id: query__route
uri: http://baeldung.com
predicates:
- Query=articleId, \w
そして、Javaの設定:
----//..route definition
.route(r -> r.query("articleId", "\w")
.id("query__route")
.uri("http://baeldung.com")
----
4.8.
RemoteAddr
ルート述語ファクトリー
RemoteAddr
Route Predicate Factoryは、CIDR表記の文字列のリスト(1以上)を取ります(例:
192.168.0.1/16
(192.168.0.1はIPアドレス、16はサブネットマスク))。
spring:
cloud:
gateway:
routes:
- id: remoteaddr__route
uri: http://baeldung.com
predicates:
- RemoteAddr=192.168.1.1/24
そして対応するJavaの設定:
----//..route definition
.route(r -> r.remoteAddr("192.168.1.1/24")
.id("remoteaddr__route")
.uri("http://baeldung.com")
----
5 Webフィルター工場
ルートフィルタは、着信HTTP要求または発信HTTP応答の変更を可能にします。
Spring Cloud Gatewayには、組み込みのWebFilterファクトリーが多数含まれています。
5.1.
AddRequestHeader
WebFilter
Factory
AddRequestHeader
WebFilterファクトリは、名前と値のパラメータを取ります。
spring:
cloud:
gateway:
routes:
- id: addrequestheader__route
uri: http://baeldung.com
predicates:
- Path=/articles
filters:
- AddRequestHeader=X-SomeHeader, bael
これは、対応するJava設定です。
----//...route definition
.route(r -> r.path("/articles")
.filters(f -> f.addRequestHeader("X-TestHeader", "rewrite__request"))
.uri("http://baeldung.com")
.id("addrequestheader__route")
----
5.2.
AddRequestParameter
WebFilterファクトリ
AddRequestParameter
WebFilterファクトリは、名前と値のパラメータを取ります。
spring:
cloud:
gateway:
routes:
- id: addrequestparameter__route
uri: http://baeldung.com
predicates:
- Path=/articles
filters:
- AddRequestParameter=foo, bar
対応するJava設定:
----//...route definition
.route(r -> r.path("/articles")
.filters(f -> f.addRequestParameter("foo", "bar"))
.uri("http://baeldung.com")
.id("addrequestparameter__route")
----
5.3.
AddResponseHeader
WebFilterファクトリ
AddResponseHeader
WebFilterファクトリは、名前と値のパラメータを取ります。
spring:
cloud:
gateway:
routes:
- id: addrequestheader__route
uri: http://baeldung.com
predicates:
- Path=/articles
filters:
- AddResponseHeader=X-SomeHeader, Bar
対応するJava設定:
----//...route definition
.route(r -> r.path("/articles")
.filters(f -> f.addResponseHeader("X-SomeHeader", "Bar"))
.uri("http://baeldung.com")
.id("addresponseheader__route")
----
5.4.
サーキットブレーカ
WebFilter
工場
Hystrix
は、Circuit-Breaker WebFilter Factoryとして使用され、Hystrixコマンドの名前である単一の名前パラメータを取ります。
spring:
cloud:
gateway:
routes:
- id: hystrix__route
uri: http://baeldung.com
predicates:
- Path=/articles
filters:
- Hystrix=someCommand
対応するJava設定:
----//...route definition
.route(r -> r.path("/articles")
.filters(f -> f.hystrix("some-command"))
.uri("http://baeldung.com")
.id("hystrix__route")
----
5.5. RedirectTo
Webフィルタ・ファクトリ
RedirectTo
WebFilterファクトリはステータスとURLパラメータを受け取ります。
ステータスは301などの300リダイレクトHTTPコードにする必要があります。
spring:
cloud:
gateway:
routes:
- id: redirectto__route
uri: http://baeldung.com
predicates:
- Path=/articles
filters:
- RedirectTo=302, http://foo.bar
そして対応するJavaの設定:
----//...route definition
.route(r -> r.path("/articles")
.filters(f -> f.redirect("302","http://foo.bar"))
.uri("http://baeldung.com")
.id("redirectto__route")
----
5.6.
RewritePath
WebFilterファクトリー
RewritePath
Web Filter Factoryは、パス正規表現パラメータと置換パラメータを取ります。これは、要求パスを書き換えるためにJava正規表現を使用します。
設定例はここにあります:
spring:
cloud:
gateway:
routes:
- id: rewritepath__route
uri: http://baeldung.com
predicates:
- Path=/articles/** **
filters:
- RewritePath=/articles/(?<articleId>.** ),/$\{articleId}
Java構成は次のように表すことができます。
----//...route definition
.route(r -> r.path("/articles")
.filters(f -> f.rewritePath("(?<articleId>.** )", articleId))
.uri("http://baeldung.com")
.id("rewritepath__route")
----
5.7.
RequestRateLimiter
WebFilterファクトリー
RequestRateLimiter WebFilterファクトリーは3つのパラメーターを取ります。
replenishRate、capacity、および
keyResolverName。
-
replenishRate
–
は、1秒あたりの要求数を表します。
ユーザーに実行を許可したい
capacity
– ** 許容できるバースト容量を定義します
-
keyResolverName
– を実装するBeanの名前です。
KeyResolver
インターフェース
KeyResolverインターフェースにより、プラガブルな戦略でリクエストを制限するためのキーを導き出すことができます。
spring:
cloud:
gateway:
routes:
- id: requestratelimiter__route
uri: http://baeldung.com
predicates:
- Path=/articles
filters:
- RequestRateLimiter=10, 50, userKeyResolver
Java構成は次のように表すことができます。
----//...route definition
.route(r -> r.path("/articles")
.filters(f -> f.requestRateLimiter().configure(c -> c.setRateLimiter(myRateLimiter)))
.uri("http://baeldung.com")
.id("requestratelimiter__route")
----
6. Spring Cloud Discoveryクライアントサポート
Spring Cloud Gatewayは、Eureka ServerやConsulなどのService DiscoveryおよびRegistryライブラリと簡単に統合できます。
@Configuration
@EnableDiscoveryClient
public class GatewayDiscoveryConfiguration {
@Bean
public DiscoveryClientRouteDefinitionLocator
discoveryClientRouteLocator(DiscoveryClient discoveryClient) {
return new DiscoveryClientRouteDefinitionLocator(discoveryClient);
}
}
6.1.
LoadBalancerClient
フィルタ
LoadBalancerClientFilter
は、
ServerWebExchangeUtils.GATEWAY
REQUEST
URL
ATTR.__を使用して、exchange属性プロパティ内のURIを探します。
URLに
lb
スキーム(例:
lb://baeldung-service)がある場合
Spring Cloud
LoadBalancerClient
を使用して名前(つまりbaeldung-service)を実際のホストとポートに解決します。
変更前の元のURLは
ServerWebExchangeUtils.GATEWAY
ORIGINAL
REQUEST
URL
ATTR
属性に配置されます。
7. モニタリング
Spring Cloud GatewayはActuator APIを利用しています。これは、アプリケーションを監視するためのいくつかのすぐに使えるサービスを提供する有名なSpring-Bootライブラリです。
Actuator APIをインストールして設定したら、
/gateway/
endpointにアクセスしてゲートウェイモニタリング機能を視覚化できます。
8実装
path
述語を使用して、Spring Cloud Gatewayをプロキシサーバーとして使用する簡単な例を作成しましょう。
8.1. 依存関係
Spring Cloud Gatewayは現在、バージョン2.0.0.RC2のマイルストーンリポジトリにあります。これも私たちがここで使っているバージョンです。
プロジェクトを追加するには、依存関係管理システムを使用します。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway</artifactId>
<version>2.0.0.RC2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
次に、必要な依存関係を追加します。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
8.2. コード実装
そして今度は
application.yml
ファイルで簡単なルーティング設定を作成します:
spring:
cloud:
gateway:
routes:
- id: baeldung__route
uri: http://baeldung.com
predicates:
- Path=/baeldung/management:
endpoints:
web:
exposure:
include: "** '
そしてゲートウェイアプリケーションコード:
@SpringBootApplication
public class GatewayApplication {
public static void main(String[]args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
アプリケーションが起動したら、URLにアクセスします。
作成されたすべてのルーティング構成をチェックする
{
"id":"baeldung__route",
"predicates":[{
"name":"Path",
"args":{"__genkey__0":"/baeldung"}
}],
"filters":[],
"uri":"http://baeldung.com",
"order":0
}
相対的なurl:
“/baeldung”
がルートとして設定されていることがわかります。 「この例で設定したとおりです。
9結論
この記事では、Spring Cloud Gatewayの一部である機能とコンポーネントについて説明しました。この新しいAPIは、ゲートウェイおよびプロキシをサポートするためのすぐに使えるツールを提供します。
ここで紹介されている例は私達のhttps://github.com/eugenp/tutorials/tree/master/spring-cloud/spring-cloud-gateway[GitHub repository]にあります。