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

การตั้งค่าการลองใหม่และหมดเวลา

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

บทเรียน 2 จาก 412 ขั้นตอน

การตั้งค่าการลองใหม่และหมดเวลา เป็นบทเรียน 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 บทเรียน

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

Build Resilient Gateways

In microservices, services can fail or become slow. To keep our applications running smoothly, we need to build resilience.

  • Resilience means your system can recover from failures and continue to function.
  • Spring Cloud Gateway provides tools to make your API Gateway more resilient.
  • Two key strategies for resilience are Timeouts and Retries.

Preventing Slow Responses with Timeouts

A timeout is a limit on how long an operation is allowed to take. If the operation doesn't complete within that time, it's automatically stopped.

  • Timeouts prevent requests from hanging indefinitely.
  • They free up resources (like network connections and threads) that would otherwise be tied up by a slow or unresponsive service.
  • In a gateway, timeouts ensure that a slow backend service doesn't slow down the entire gateway or other requests.

Configuring Read Timeouts

Spring Cloud Gateway allows you to configure specific timeouts for routes. The ReadTimeout filter is commonly used to limit how long the gateway waits for a response from the backend service after the connection is established.

  • This timeout is applied per route.
  • It helps prevent a single slow backend from impacting the gateway's overall performance.
  • The value is typically set in milliseconds.

Read Timeout Configuration Example

Here's how you can configure a ReadTimeout for a specific route in your application.yml. This example sets a 5-second read timeout for requests to /service-a/**:

Remember, this is part of your Spring Boot application's configuration.

spring:
  cloud:
    gateway:
      routes:
        - id: service_a_route
          uri: http://localhost:8081
          predicates:
            - Path=/service-a/**
          filters:
            - ReadTimeout=5000

Handling Transient Failures with Retries

Retries involve automatically re-sending a request that has failed, hoping it will succeed on a subsequent attempt.

  • They are ideal for transient failures: temporary issues like network glitches or a brief service restart.
  • Retries should be used cautiously, especially for non-idempotent operations (actions that produce different results if performed multiple times).
  • Spring Cloud Gateway can be configured to automatically retry requests to backend services.

The Retry GatewayFilter

Spring Cloud Gateway provides a Retry filter to enable automatic retries for failed requests. You can configure various aspects of the retry logic:

  • retries: The maximum number of retry attempts.
  • statuses: HTTP status codes that should trigger a retry (e.g., 503 for Service Unavailable).
  • methods: HTTP methods that can be retried (e.g., GET, PUT).

Retry Configuration Example

Let's configure a Retry filter. This example retries requests up to 3 times if the backend returns a 5XX error or a 404, specifically for GET requests to /service-b/**:

spring:
  cloud:
    gateway:
      routes:
        - id: service_b_route
          uri: http://localhost:8082
          predicates:
            - Path=/service-b/**
          filters:
            - name: Retry
              args:
                retries: 3
                statuses: 
                  - SERVER_ERROR
                  - NOT_FOUND
                methods:
                  - GET

Simple Retry Logic Demo

While Spring Cloud Gateway handles retries via configuration, the core concept involves looping until success or max attempts. Here's a basic Java program demonstrating a retry loop:

public class RetryDemo {
  private static int attempt = 0;

  public static boolean simulateBackendCall() {
    System.out.println("Attempt " + (++attempt));
    return attempt < 3; // Fails for first 2 attempts
  }

  public static void main(String[] args) {
    int maxRetries = 2;
    for (int i = 0; i <= maxRetries; i++) {
      if (!simulateBackendCall()) {
        System.out.println("Success!");
        return;
      }
      System.out.println("Failed. Retrying...");
      try { Thread.sleep(100); } catch (InterruptedException e) {}
    }
    System.out.println("Max retries reached. Operation failed.");
  }
}

Combining Timeouts & Retries

Timeouts and retries often work together:

  • A timeout can trigger a retry if the request doesn't complete within the specified time.
  • If a request times out, the gateway might then attempt a retry, hoping the next attempt will be faster or the service will respond.
  • It's crucial to configure these carefully to avoid endless loops or excessive delays. For example, a retry might happen *after* a read timeout, or a global timeout could encompass all retries.

Best Practices for Resilience

When implementing timeouts and retries, consider these best practices:

  • Idempotency: Only retry idempotent operations (e.g., GET, PUT) unless you have specific logic to handle non-idempotent ones (e.g., POST).
  • Exponential Backoff: Introduce increasing delays between retries to avoid overwhelming a struggling service.
  • Circuit Breakers: Combine with circuit breakers (covered in Lesson 10.1) to stop retrying services that are clearly down.
  • Monitoring: Monitor retry counts and timeouts to identify persistently problematic services.

Quick Check on Gateway Resilience

You're configuring a Spring Cloud Gateway route for a backend service that sometimes experiences brief network hiccups, resulting in a 503 Service Unavailable error. You want the gateway to automatically try the request again a few times before giving up. Which filter and configuration would best achieve this?

Recap: Timeouts & Retries

We've explored how Timeouts and Retries are fundamental for building resilient API Gateways with Spring Cloud Gateway.

  • Timeouts prevent requests from hanging, freeing up resources.
  • The ReadTimeout filter configures the wait time for backend responses.
  • Retries automatically re-send requests for transient failures.
  • The Retry filter allows fine-grained control over retry attempts, statuses, and HTTP methods.
  • Combining these with best practices helps create robust microservice architectures.
เริ่มต้นได้ฟรี

เรียนรู้ API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
12
บทเรียน
48

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

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

ใช่ — ข้อความเต็มของ “การตั้งค่าการลองใหม่และหมดเวลา” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ 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 ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. เซอร์กิตเบรกเกอร์ด้วย Resilience4j
  2. การตั้งค่าการลองใหม่และหมดเวลา
  3. การจัดการข้อผิดพลาดและทางเลือกสำรอง
  4. กำแพงกั้นและการจำกัดอัตราเพื่อความทนทาน
← กลับไปที่ API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)