ตัวกรองคำขอและการตอบกลับแบบกำหนดเอง
พัฒนาตัวกรองแบบกำหนดเองของคุณเอง เพื่อแทรกตรรกะเฉพาะสำหรับแก้ไขคำขอขาเข้า หรือการตอบกลับขาออก
ตัวกรองคำขอและการตอบกลับแบบกำหนดเอง เป็นบทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Custom Filters?
Spring Cloud Gateway offers many built-in filters, but sometimes you need very specific logic. Custom filters let you inject your own code into the request/response flow.
This allows for highly tailored processing, such as custom authentication checks, unique logging formats, or specific header manipulations.
The GatewayFilter Interface
To create a custom filter, you'll implement the GatewayFilter interface. This interface has one main method: filter().
ServerWebExchange exchange: Provides access to the HTTP request and response.GatewayFilterChain chain: Allows you to pass the request to the next filter or the target service.
You'll also often implement Ordered to define your filter's execution priority.
Basic Request Logger Filter
Let's create a simple filter that logs the incoming request path and method. This filter will run before the request is forwarded to the backend service.
Notice how chain.filter(exchange) is called to continue the processing.
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
public class MyLoggingFilter implements GatewayFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
System.out.println("Incoming Request:");
System.out.println(" Path: " + exchange.getRequest().getPath());
System.out.println(" Method: " + exchange.getRequest().getMethod());
return chain.filter(exchange); // Pass to next filter/service
}
@Override
public int getOrder() {
return -1; // Execute early
}
public static void main(String[] args) {
MyLoggingFilter filter = new MyLoggingFilter();
System.out.println("This filter logs request details.");
System.out.println("In a Spring Gateway app, this code runs for each matched request.");
System.out.println("The 'filter' method is the core logic, 'getOrder' sets priority.");
}
}Registering Your Custom Filter
Once you've created your filter class, you need to tell Spring Cloud Gateway to use it. You can register it either in your application.yml or programmatically.
For simple filters, registering directly on a route is common. For more complex, reusable filters, a filter factory is often used (covered later).
spring:
cloud:
gateway:
routes:
- id: my_custom_route
uri: http://localhost:8081
predicates:
- Path=/api/**
filters:
- MyLoggingFilter # Name of your @Component filterAccessing Request & Response
The ServerWebExchange object is your gateway to everything about the current HTTP interaction. It contains the ServerHttpRequest and ServerHttpResponse.
exchange.getRequest(): Get details about the incoming request (headers, body, path).exchange.getResponse(): Modify the outgoing response (headers, status code).
Remember, these are reactive types, so operations often return Mono or Flux.
Modifying Request Headers
You might need to add or modify headers before forwarding a request to a backend service. For example, injecting an authentication token or a tracing ID.
Since ServerHttpRequest is immutable, you must build a new request using mutate() and then update the exchange.
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
public class AddAuthHeaderFilter implements GatewayFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String authToken = "my-secret-token-123"; // Get from config/service
ServerWebExchange mutatedExchange = exchange.mutate()
.request(builder -> builder.header("X-Auth-Token", authToken))
.build();
System.out.println("Added X-Auth-Token header to request.");
return chain.filter(mutatedExchange); // Use the mutated exchange
}
@Override
public int getOrder() {
return 0; // After logging, before forwarding
}
public static void main(String[] args) {
AddAuthHeaderFilter filter = new AddAuthHeaderFilter();
System.out.println("This filter adds an 'X-Auth-Token' header.");
System.out.println("It uses 'exchange.mutate().request(...).build()' to modify the request.");
}
}Modifying Response Headers
Custom filters can also modify the response *after* the backend service has sent its reply. This is useful for adding security headers, caching directives, or custom metadata.
The trick is to use exchange.getResponse().beforeCommit() to hook into the response lifecycle, or reactive chaining.
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
public class AddResponseHeaderFilter implements GatewayFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
// This code runs AFTER the response from backend is received
exchange.getResponse().getHeaders().add("X-Gateway-Processed", "true");
System.out.println("Added X-Gateway-Processed header to response.");
}));
}
@Override
public int getOrder() {
return 1; // After request processing
}
public static void main(String[] args) {
AddResponseHeaderFilter filter = new AddResponseHeaderFilter();
System.out.println("This filter adds 'X-Gateway-Processed' to the response.");
System.out.println("It uses 'chain.filter(exchange).then(Mono.fromRunnable(...))' for post-processing.");
}
}Controlling Filter Order
When you have multiple custom filters, their execution order matters. The Ordered interface (and its getOrder() method) lets you define this.
- Lower values (e.g.,
-1) mean higher priority (execute earlier). - Higher values (e.g.,
1) mean lower priority (execute later). - Filters with the same order might run in an undefined sequence.
Use Ordered.HIGHEST_PRECEDENCE or LOWEST_PRECEDENCE for extreme cases.
Custom GatewayFilter Factories
For more advanced scenarios, especially when your filter needs configuration (e.g., a specific header name, a threshold value), you can create a GatewayFilterFactory.
This allows you to define a filter with parameters that can be configured directly in your application.yml, making your filters highly reusable and flexible.
You'd extend AbstractGatewayFilterFactory and define a configuration class for its properties.
Filter Logic Check
Consider a custom GatewayFilter that needs to both add a request header and then, after the backend responds, add a response header. Which parts of the filter() method would you modify?
Recap: Custom Filter Power
You've learned how to create custom GatewayFilters in Spring Cloud Gateway. These filters are powerful tools for injecting specific logic into your API Gateway's request and response flow.
- Implement
GatewayFilterandOrdered. - Use
ServerWebExchangefor request/response access. - Mutate requests and use reactive chaining for response modification.
- Control execution order with
getOrder().
Custom filters give you fine-grained control to tailor your gateway's behavior precisely.
คำถามที่พบบ่อย
บทเรียน “ตัวกรองคำขอและการตอบกลับแบบกำหนดเอง” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ตัวกรองคำขอและการตอบกลับแบบกำหนดเอง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ 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 ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “ตัวกรองคำขอและการตอบกลับแบบกำหนดเอง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) นี้ได้ไหม
ได้ บทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ตัวกรองส่วนกลางและ GatewayFilterFactory
- ตัวกรองคำขอและการตอบกลับแบบกำหนดเอง
- การประมวลผลก่อนและหลังด้วยตัวกรอง
- GatewayFilters ในตัวที่ควรรู้จัก