0Pricing
API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) · レッスン

グローバルフィルターとGatewayFilterFactory

グローバルフィルターの概念と、組み込みのGatewayFilterFactoryを使って一般的な変換を行う方法を理解します。

「グローバルフィルターとGatewayFilterFactory」はCoddyKit上の無料API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)レッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAPI Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)コースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

What are Gateway Filters?

In Spring Cloud Gateway, filters are like interceptors that allow you to modify incoming HTTP requests or outgoing HTTP responses.

They provide a powerful way to implement cross-cutting concerns for your API traffic, such as security, logging, or data transformation.

Pre- and Post-Filters

Spring Cloud Gateway supports two main types of filter execution:

  • Pre-filters: Executed before the request is sent to the downstream service. Great for authentication, logging, or modifying request headers.
  • Post-filters: Executed after the response is received from the downstream service but before it's sent back to the client. Useful for modifying responses, caching, or error handling.

Understanding Global Filters

A Global Filter is applied to every single request that passes through the gateway, regardless of the specific route it matches.

This makes them ideal for concerns that affect all your API traffic, like global logging, security checks, or metrics collection across all services.

They implement the GlobalFilter interface.

Building a Custom Global Filter

Let's create a simple global filter that logs the incoming request path. It needs to implement GlobalFilter and Ordered.

Run this Spring Boot app and access http://localhost:8080/test/hello. You'll see the log in the console!

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@SpringBootApplication
public class GatewayApp {

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

    // A simple route for demonstration
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
            .route("test_route", r -> r.path("/test/**")
                .uri("http://httpbin.org:80")) // Public test service
            .build();
    }

    @Component
    static class MyLoggingFilter implements GlobalFilter, Ordered {
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            System.out.println("Global Filter: Request Path -> " + exchange.getRequest().getPath());
            return chain.filter(exchange); // Continue filter chain
        }

        @Override
        public int getOrder() {
            return -1; // Execute very early
        }
    }
}

Understanding Filter Order

When multiple filters (global or route-specific) are present, their execution order matters.

Filters that implement the Ordered interface define their priority using the getOrder() method. Lower values mean higher priority (executed earlier).

  • Negative values: Very high priority.
  • Positive values: Lower priority.
  • Filters without an explicit order often run later.

What is a GatewayFilterFactory?

While GlobalFilters apply everywhere, a GatewayFilterFactory provides reusable, configurable filters that you can apply to specific routes.

Spring Cloud Gateway comes with many built-in factories for common tasks, like adding/removing headers, rewriting paths, or applying rate limits. You configure them per route.

AddRequestHeader Factory in Action

The AddRequestHeader factory adds a static header to the request before it's forwarded to the backend service.

Run this example and navigate to http://localhost:8080/add-header/test. The response from httpbin.org will show the added header!

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class GatewayApp {

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

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
            .route("add_header_route", r -> r.path("/add-header/**")
                .filters(f -> f.addRequestHeader("X-Gateway-Custom", "CoddyKit"))
                .uri("http://httpbin.org:80/headers")) // Shows request headers
            .build();
    }
}

Exploring More Built-in Factories

Spring Cloud Gateway offers many other powerful GatewayFilterFactory implementations:

  • RemoveRequestHeader: Removes a specified header.
  • RewritePath: Changes the request URI path.
  • Retry: Retries failed requests.
  • RateLimiter: Applies rate limiting to requests.

These factories simplify common gateway tasks without writing custom code.

Global vs. Route-Specific Filters

When should you use a Global Filter versus a GatewayFilterFactory?

  • Choose Global Filters for: Cross-cutting concerns affecting all requests (e.g., global security, logging).
  • Choose GatewayFilterFactory (route-specific) for: Logic specific to certain APIs or groups of routes (e.g., API versioning, specific header manipulation, rate limiting on a particular endpoint).

Global Filter Check

Consider a Spring Cloud Gateway application. Which statement is TRUE about Global Filters?

Global Filters & Factories Recap

We've explored Global Filters, which apply to all requests, and learned how to create a custom one. We also introduced GatewayFilterFactory, which offers reusable, configurable filters for specific routes.

Understanding these filter types and when to use them is crucial for building powerful and flexible API Gateways with Spring Cloud Gateway.

よくある質問

「グローバルフィルターとGatewayFilterFactory」レッスンは無料ですか?

はい。「グローバルフィルターとGatewayFilterFactory」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)コースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)コースには全4レッスンが含まれています。

「グローバルフィルターとGatewayFilterFactory」で何を学びますか?

グローバルフィルターの概念と、組み込みのGatewayFilterFactoryを使って一般的な変換を行う方法を理解します。 ブラウザで直接実行するハンズオンコードでAPI Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)を演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)を始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAPI Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)は初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「グローバルフィルターとGatewayFilterFactory」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAPI Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)レッスンでコードを書いて実行できますか?

はい。すべてのAPI Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)レッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. グローバルフィルターとGatewayFilterFactory
  2. カスタムリクエスト/レスポンスフィルター
  3. フィルターによる前処理と後処理
  4. 知っておきたい組み込みGatewayFilter
← API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)に戻る