0Pricing
API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) · บทเรียน

การประมวลผลก่อนและหลังด้วยตัวกรอง

ใช้ตัวกรองเพื่อดำเนินการก่อนที่คำขอจะไปถึงบริการ และหลังจากบริการตอบกลับแล้ว

การประมวลผลก่อนและหลังด้วยตัวกรอง เป็นบทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Intro to Pre/Post Filters

Welcome! In this lesson, we'll explore how Spring Cloud Gateway filters can process requests before they reach a backend service (pre-processing) and after the service responds (post-processing).

This fine-grained control is crucial for handling complex API gateway tasks.

The Filter Chain Revisited

Recall that filters operate in a chain. Each GatewayFilter or GlobalFilter can perform actions:

  • Before calling chain.filter(exchange): This is pre-processing.
  • After chain.filter(exchange) returns a Mono<Void>: This is post-processing.

The reactive nature of Spring Cloud Gateway, using Mono, makes this sequential execution powerful.

Pre-Processing: Before the Service

Pre-processing filters execute before the gateway forwards the request to your actual backend service. Think of them as interceptors for incoming requests.

Common pre-processing tasks include:

  • Authenticating and authorizing requests
  • Adding or modifying request headers
  • Rewriting the URL path or query parameters
  • Implementing rate limiting

Pre-Filter Example: Add Header

Let's look at a simple pre-processing example: adding a custom header to the request before it reaches the service. Spring Cloud Gateway provides built-in filters like AddRequestHeader for this.

This configuration adds an X-Request-Source header with the value gateway to all requests matching the path /api/pre/**.

spring:
  cloud:
    gateway:
      routes:
        - id: pre_header_route
          uri: http://localhost:8080/service/echo
          predicates:
            - Path=/api/pre/**
          filters:
            - AddRequestHeader=X-Request-Source, gateway

Runnable Pre-Filter Code

Try running this full Spring Boot application. It sets up a gateway that adds a request header and routes to a simple echo endpoint within the same application. Check the backend's console or response to see 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;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class GatewayApp {

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

  // Dummy backend service to echo headers
  @GetMapping("/service/echo")
  public String echoHeaders(@RequestHeader(required = false) java.util.Map<String, String> headers) {
    return "Backend received headers: " + headers.get("x-request-source");
  }

  @Bean
  public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
      .route("pre_header_route", r -> r.path("/api/pre/**")
        .filters(f -> f.addRequestHeader("X-Request-Source", "gateway"))
        .uri("http://localhost:8080/service/echo")) // Route to its own dummy backend
      .build();
  }
}

Post-Processing: After the Service

Post-processing filters execute after the backend service has responded but before the gateway sends that response back to the client.

This allows you to inspect or modify the backend's response.

Typical post-processing tasks include:

  • Modifying response headers or body
  • Logging response details (status, latency)
  • Adding metrics for response processing
  • Implementing response caching

Custom Post-Processing Filter

For post-processing, you often need to create custom filters. These filters use the Mono returned by chain.filter(exchange) to add logic that executes upon successful completion.

The .then(Mono.fromRunnable(() -> { ... })) pattern is common for post-processing actions.

Runnable Post-Filter Code

Here's a full Spring Boot application with a custom GlobalFilter that adds a X-Post-Processed header to every response. Notice how the filter logic is chained using .then(Mono.fromRunnable(...)).

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
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.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@SpringBootApplication
@RestController
public class GatewayApp {

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

  // Dummy backend service
  @GetMapping("/service/data")
  public String getData() {
    return "Backend response data!";
  }

  @Bean
  public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
      .route("post_filter_route", r -> r.path("/api/post/**")
        .uri("http://localhost:8080/service/data")) // Route to itself
      .build();
  }
}

@Component
class CustomPostFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // This code runs AFTER the downstream service responds
            exchange.getResponse().getHeaders().add("X-Post-Processed", "true");
            System.out.println("Post-processing: Added X-Post-Processed header.");
        }));
    }

    @Override
    public int getOrder() {
        return -1; // Execute relatively late in the filter chain
    }
}

Pre vs. Post: Key Differences

Understanding when to use pre vs. post processing is key:

  • Pre-filters: Act on the request before it leaves the gateway. Ideal for security, routing logic, request transformation.
  • Post-filters: Act on the response after it returns from the backend. Ideal for response transformation, logging response details, metrics collection.

Choose the right stage to efficiently manage your API traffic.

Filter Timing Challenge

Consider a Spring Cloud Gateway setup. Which of these tasks are typically performed by filters before forwarding a request to a backend service?

Recap: Pre/Post Processing

Great job! You've learned about the powerful concept of pre-processing and post-processing with Spring Cloud Gateway filters.

  • Pre-filters modify requests before they hit the backend.
  • Post-filters modify responses after the backend has replied.
  • The reactive Mono chain enables precise control over filter execution timing.

This understanding is vital for building robust and feature-rich API gateways!

คำถามที่พบบ่อย

บทเรียน “การประมวลผลก่อนและหลังด้วยตัวกรอง” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การประมวลผลก่อนและหลังด้วยตัวกรอง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การประมวลผลก่อนและหลังด้วยตัวกรอง”

ใช้ตัวกรองเพื่อดำเนินการก่อนที่คำขอจะไปถึงบริการ และหลังจากบริการตอบกลับแล้ว คุณปฏิบัติ API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การประมวลผลก่อนและหลังด้วยตัวกรอง” ใช้เวลานานแค่ไหน

บทเรียน 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)