1. 概要

In this tutorial, we’ll explore the main features of the Spring Cloud Gateway project, a new API based on Spring 5, Spring Boot 2 and Project Reactor.

このツールは、単一のファサードの背後に複数のサービスを隠す方法として、マイクロサービスアプリケーションでよく使用されるすぐに使用できるルーティングメカニズムを提供します。

Spring Cloud Gatewayプロジェクトを使用しないゲートウェイパターンの説明については、以前の記事をご覧ください。

2. ルーティングハンドラー

Being focused on routing requests, the Spring Cloud Gateway forwards requests to a Gateway Handler Mapping, which determines what should be done with requests matching a specific route.

Let’s start with a quick example of how the Gateway Handler resolves route configurations by using 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 — the primary API of the gateway. It is defined by a given identification (ID), a destination (URI) and set of predicates and filters.
  • Predicate — a Java 8 Predicate — which is used for matching HTTP requests using headers, methods or parameters
  • Filter — a standard Spring WebFilter

3. 動的ルーティング

Zuul と同様に、SpringCloudGatewayはさまざまなサービスにリクエストをルーティングする手段を提供します。

The routing configuration can be created by using pure Java (RouteLocator, as shown in the example in Section 2) or by using properties configuration:

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インフラストラクチャを使用してルートを照合します。

また、多くの組み込みルート述語ファクトリが含まれています。 All these predicates match different attributes of the HTTP request. 複数のルート述語ファクトリは、論理「and」を介して組み合わせることができます。

Route matching can be applied both programmatically and via configuration properties file using a different type of Route Predicate Factories.

私たちの記事SpringCloud Gateway Routing Predicate Factory では、ルーティングファクトリについて詳しく説明しています。

5. WebFilterファクトリ

ルートフィルターを使用すると、着信HTTP要求または発信HTTP応答を変更できます。

Spring Cloud Gatewayには、多くの組み込みWebFilterファクトリと、カスタムフィルタを作成する機能が含まれています。

私たちの記事SpringCloud Gateway WebFilter Factorys は、WebFilterファクトリをより詳細に調査しています。

6. SpringCloudDiscoveryClientのサポート

Spring Cloud Gatewayは、EurekaServerやConsulなどのServiceDiscoveryおよびRegistryライブラリと簡単に統合できます。

@Configuration
@EnableDiscoveryClient
public class GatewayDiscoveryConfiguration {
 
    @Bean
    public DiscoveryClientRouteDefinitionLocator 
      discoveryClientRouteLocator(DiscoveryClient discoveryClient) {
 
        return new DiscoveryClientRouteDefinitionLocator(discoveryClient);
    }
}

6.1. LoadBalancerClientフィルター

The LoadBalancerClientFilter looks for a URI in the exchange attribute property using ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR.

If the URL has a lb scheme (e.g., lb://baeldung-service), it’ll use the Spring Cloud LoadBalancerClient to resolve the name (i.e., baeldung-service) to an actual host and port.

変更されていない元のURLは、ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR属性に配置されます。

7. モニタリング

Spring Cloud Gateway makes use of the Actuator API, a well-known Spring Boot library that provides several out-of-the-box services for monitoring the application.

Actuator APIをインストールして構成すると、 / gateway/エンドポイントにアクセスしてゲートウェイ監視機能を視覚化できます。

8. 実装

次に、パス述語を使用して、プロキシサーバーとしてSpring Cloudゲートウェイを使用する簡単な例を作成します。

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: "*'

And here’s the Gateway application code:

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

After the application starts, we can access the url “http://localhost/actuator/gateway/routes/baeldung_route” to check all routing configuration created:

{
    "id":"baeldung_route",
    "predicates":[{
        "name":"Path",
        "args":{"_genkey_0":"/baeldung"}
    }],
    "filters":[],
    "uri":"http://baeldung.com",
    "order":0
}

We see that the relative url “/baeldung” is configured as a route. So, hitting the url “http://localhost/baeldung”, we’ll be redirected to “http://baeldung.com”, as was configured in our example.

9. 結論

この記事では、SpringCloudGatewayの一部である機能とコンポーネントのいくつかについて説明しました。 この新しいAPIは、ゲートウェイとプロキシをサポートするためのすぐに使用できるツールを提供します。

ここに示されている例は、GitHubリポジトリにあります。