0Pricing
API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) · 课时

全局过滤器与 GatewayFilterFactory

了解全局过滤器的概念,以及如何使用内置的 GatewayFilterFactories 执行常见转换。

全局过滤器与 GatewayFilterFactory 是 CoddyKit 上的免费 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 课程的其余内容,请升级到 CoddyKit PRO。 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 课程共包含 4 节课。

「全局过滤器与 GatewayFilterFactory」这节课中我会学到什么?

了解全局过滤器的概念,以及如何使用内置的 GatewayFilterFactories 执行常见转换。 你通过在浏览器中直接运行的动手代码来练习 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway),全天候 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. 您应了解的内置 GatewayFilters
← 返回 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)