0Pricing
Microservices Communication Patterns (Saga, Circuit Breaker) · บทเรียน

การนำกลไกสำรองและการหมดเวลาการรอไปใช้

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

การนำกลไกสำรองและการหมดเวลาการรอไปใช้ เป็นบทเรียน Microservices Communication Patterns (Saga, Circuit Breaker) ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Microservices Communication Patterns (Saga, Circuit Breaker) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Microservices Communication Patterns (Saga, Circuit Breaker) มีบทเรียนทั้งหมด 4 บทเรียน

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

Welcome to Resilience Patterns

In this lesson, we'll dive into two crucial patterns for building resilient microservices: Fallbacks and Timeouts.

These patterns help your applications gracefully handle failures and slow responses from other services, making your system more robust and reliable.

What is a Fallback?

A fallback mechanism provides an alternative course of action when a primary operation fails or encounters an error.

  • It ensures your application can still respond, even if partially, instead of completely failing.
  • Think of it as a plan B for your service calls.
  • This leads to graceful degradation, where the system provides reduced functionality rather than total failure.

Fallback in Action: Default Data

Imagine an e-commerce site. If the service providing personalized product recommendations fails, you wouldn't want the entire page to break.

A fallback could display:

  • Popular items (default list)
  • Cached recommendations
  • A simple message like 'Recommendations currently unavailable'

The user experience remains intact, even with a minor issue.

Coding a Simple Fallback

Let's see a basic Java example. Here, if our 'external service' throws an error, we catch it and return a default value instead of letting the application crash.

public class FallbackExample {

  public String getProductRecommendation() {
    try {
      // Simulate calling an external service that might fail
      if (Math.random() < 0.5) {
        throw new RuntimeException("Service unavailable!");
      }
      return "Personalized Recommendation A";
    } catch (Exception e) {
      // Fallback: return a default recommendation
      System.out.println("Fallback activated: " + e.getMessage());
      return "Default Popular Product";
    }
  }

  public static void main(String[] args) {
    FallbackExample app = new FallbackExample();
    System.out.println("Recommendation: " + app.getProductRecommendation());
    System.out.println("Recommendation: " + app.getProductRecommendation());
  }
}

Why Do We Need Timeouts?

While fallbacks handle failures, timeouts address slow responses. A service might not fail outright, but it could take too long to respond.

  • Resource Exhaustion: Waiting indefinitely ties up resources (threads, connections).
  • Cascading Failures: A slow service can make other dependent services slow, leading to a system-wide slowdown.

Timeouts set a maximum duration for an operation.

Types of Timeouts

When making network calls, you'll often encounter different types of timeouts:

  • Connection Timeout: The maximum time allowed to establish a connection to the remote service. If no connection is made within this time, it fails.
  • Read Timeout: The maximum time allowed for data to be received after the connection is established. If the service stops sending data, this timeout triggers.
  • Request Timeout: An overall timeout for the entire operation, from start to finish. This often encompasses both connection and read timeouts.

Setting a Request Timeout

In Java, setting timeouts depends on the client library you're using (e.g., OkHttp, HttpClient). Conceptually, it looks like this:

HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(5)) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://slowservice.com/data")) .timeout(Duration.ofSeconds(10)) // Request timeout .GET() .build();

This ensures your request won't hang forever.

Combining Timeout & Fallback

Timeouts and fallbacks are powerful when used together. A timeout triggers a failure, which can then be handled by a fallback.

Let's extend our previous example. We'll simulate a slow service call. If it takes too long, a timeout will occur, and our fallback will provide a default response.

import java.util.concurrent.*;

public class TimeoutFallbackExample {

  public String getProductRecommendationWithTimeout() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
      Future<String> future = executor.submit(() -> {
        // Simulate a slow external service
        long delay = (long) (Math.random() * 3000) + 1000; // 1-4 seconds
        Thread.sleep(delay);
        return "Personalized Recommendation B";
      });

      // Wait for the result, but only for 2 seconds
      return future.get(2, TimeUnit.SECONDS);

    } catch (TimeoutException e) {
      System.out.println("Timeout occurred: " + e.getMessage());
      return "Fallback: Timed out default product";
    } catch (Exception e) {
      System.out.println("Other error: " + e.getMessage());
      return "Fallback: Error default product";
    } finally {
      executor.shutdown();
    }
  }

  public static void main(String[] args) {
    TimeoutFallbackExample app = new TimeoutFallbackExample();
    System.out.println("Recommendation: " + app.getProductRecommendationWithTimeout());
    System.out.println("Recommendation: " + app.getProductRecommendationWithTimeout());
  }
}

Benefits of Using Both

By combining timeouts and fallbacks, you achieve a higher level of resilience:

  • Improved User Experience: Users don't wait indefinitely for a page to load or an operation to complete.
  • Resource Protection: Your services don't exhaust resources waiting for unresponsive dependencies.
  • System Stability: Prevents cascading failures, where one slow service brings down many others.
  • Predictable Behavior: Your system behaves predictably even under stress.

Quick Check: Resilience

You are designing a microservice that calls an external payment gateway. If the gateway is slow or unavailable, you want to:

  • Prevent your service from hanging indefinitely.
  • Show a 'Payment currently unavailable' message to the user instead of an error page.

Which resilience patterns should you prioritize for this scenario?

Recap: Fallbacks & Timeouts

Great job! You've learned about two essential resilience patterns:

  • Fallbacks: Provide alternative responses to gracefully handle failures, ensuring a better user experience.
  • Timeouts: Set limits on how long an operation can take, preventing resource exhaustion and cascading failures from slow services.

Using these patterns together makes your microservices more robust and reliable.

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

บทเรียน “การนำกลไกสำรองและการหมดเวลาการรอไปใช้” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การนำกลไกสำรองและการหมดเวลาการรอไปใช้” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Microservices Communication Patterns (Saga, Circuit Breaker) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Microservices Communication Patterns (Saga, Circuit Breaker) มีบทเรียนทั้งหมด 4 บทเรียน

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

สำรวจวิธีนำกลไกสำรองและการหมดเวลาการรอไปใช้ เพื่อจัดการกับบริการที่ไม่พร้อมใช้งานหรือการตอบสนองที่ล่าช้าอย่างเหมาะสม คุณปฏิบัติ Microservices Communication Patterns (Saga, Circuit Breaker) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Microservices Communication Patterns (Saga, Circuit Breaker) หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Microservices Communication Patterns (Saga, Circuit Breaker) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

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

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Microservices Communication Patterns (Saga, Circuit Breaker) นี้ได้ไหม

ได้ บทเรียน Microservices Communication Patterns (Saga, Circuit Breaker) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. เหตุใดความทนทานจึงสำคัญ
  2. พื้นฐานรูปแบบการลองใหม่
  3. การนำกลไกสำรองและการหมดเวลาการรอไปใช้
  4. รูปแบบ Bulkhead
← กลับไปที่ Microservices Communication Patterns (Saga, Circuit Breaker)