0Pricing
API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) · 강의

필터를 사용한 사전 및 사후 처리

요청이 서비스에 도달하기 전(사전)과 서비스가 응답한 후(사후)에 수행할 작업에 필터를 적용해 보세요.

필터를 사용한 사전 및 사후 처리은(는) CoddyKit의 무료 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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!

자주 묻는 질문

“필터를 사용한 사전 및 사후 처리” 강의는 무료인가요?

네 — “필터를 사용한 사전 및 사후 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의 전체를 잠금 해제할 수 있습니다. API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의에는 총 4개의 강의가 포함되어 있습니다.

“필터를 사용한 사전 및 사후 처리”에서 뭘 배우나요?

요청이 서비스에 도달하기 전(사전)과 서비스가 응답한 후(사후)에 수행할 작업에 필터를 적용해 보세요. 브라우저에서 직접 실행하는 실습 코드로 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“필터를 사용한 사전 및 사후 처리” 강의는 얼마나 걸리나요?

대부분의 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)(으)로 돌아가기