0Pricing
Spring Boot 4 Microservices & REST APIs · บทเรียน

การใช้ Fallback และ Timeout

กำหนดค่า fallback และ timeout ที่รองรับความผิดพลาดอย่างเหมาะสมสำหรับการเรียกบริการที่ไม่น่าเชื่อถือ

การใช้ Fallback และ Timeout เป็นบทเรียน Spring Boot 4 Microservices & REST APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Microservices & REST APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 3 บทเรียน

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

Building Resilient Services

In microservices, services often depend on each other. What happens if one service is slow or fails?

This lesson explores timeouts and fallbacks, crucial patterns to make your applications resilient to such issues.

Dealing with Unreliable Calls

Imagine your user service calls a product service. If the product service hangs, your user service might wait indefinitely.

  • Resource Drain: Threads get stuck, consuming memory and CPU.
  • Poor User Experience: Users face long waits or unresponsive apps.
  • Cascading Failures: One slow service can bring down others.

Understanding Call Timeouts

A timeout is a maximum duration an operation is allowed to take. If the operation doesn't complete within this time, it's aborted.

  • Connection Timeout: How long to wait to establish a connection.
  • Read Timeout: How long to wait for data after a connection is established.

Timeouts prevent your application from waiting forever for an unresponsive service.

Configuring Basic Timeouts

You can configure timeouts for HTTP clients like Spring's RestTemplate or WebClient. This example shows a simple RestTemplate setup.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import java.time.Duration;

@SpringBootApplication
public class TimeoutApp {

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

  @Bean
  public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder
        .setConnectTimeout(Duration.ofSeconds(1)) // 1 second to connect
        .setReadTimeout(Duration.ofSeconds(2))    // 2 seconds to read data
        .build();
  }
  
  // In a real app, you'd inject and use this RestTemplate
  // e.g., restTemplate.getForObject("http://localhost:8081/slow-service", String.class);
}

Graceful Degradation with Fallbacks

Even with timeouts, a service call might still fail (e.g., due to network issues or service unavailability). A fallback provides an alternative action or default value when the primary operation fails.

This ensures your application can still respond gracefully, even if with limited functionality.

Simple Fallback Logic

You can implement fallbacks manually using try-catch blocks. This allows you to handle exceptions and return a default response.

Consider a simple method that fetches user details:

public class UserService {

  public String getUserName(int userId) {
    try {
      // Simulate a network call that might fail
      if (userId == 101) {
        throw new RuntimeException("Service unavailable!");
      }
      return "User " + userId + " Details";
    } catch (Exception e) {
      // This is our fallback logic!
      System.out.println("Error fetching user " + userId + ". Returning default.");
      return "Guest User"; // Fallback value
    }
  }

  public static void main(String[] args) {
    UserService service = new UserService();
    System.out.println(service.getUserName(100)); // Works
    System.out.println(service.getUserName(101)); // Fails, returns fallback
  }
}

Resilience4j for Fallbacks

Manually managing fallbacks can become complex. Libraries like Resilience4j provide declarative ways to implement resilience patterns, including fallbacks.

Resilience4j integrates well with Spring Boot and allows you to specify a fallbackMethod that gets called when the primary method fails.

Declarative Fallbacks with Resilience4j

Using Resilience4j's @CircuitBreaker annotation, you can define a fallbackMethod. This method will be invoked if the main method fails or the circuit breaker is open.

First, you'd need the Resilience4j dependency. Then, you can apply it:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;

@SpringBootApplication
@RestController
public class ResilienceApp {

  @Autowired
  private ProductService productService;

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

  @GetMapping("/product-info")
  public String getProductDetails() {
    return productService.getProduct();
  }
}

@Service
class ProductService {
  private int callCount = 0;

  @CircuitBreaker(name = "productService", fallbackMethod = "fallbackGetProduct")
  public String getProduct() {
    callCount++;
    if (callCount % 3 != 0) { // Simulate failure 2 out of 3 times
      throw new RuntimeException("Product service is down!");
    }
    return "Product A Details";
  }

  // This is the fallback method
  public String fallbackGetProduct(Throwable t) {
    System.out.println("Fallback activated: " + t.getMessage());
    return "Default Product (Fallback)";
  }
}

Apply Your Knowledge

You have a microservice that calls an external payment gateway. This gateway is sometimes slow or fails.

Which combination of resilience patterns would best ensure your service remains responsive and provides a user-friendly experience, even if the payment gateway is unreliable?

Lesson Summary

We've learned how timeouts and fallbacks are essential for building robust microservices:

  • Timeouts prevent service calls from hanging indefinitely, saving resources.
  • Fallbacks provide alternative responses when primary operations fail, ensuring graceful degradation.

These patterns improve user experience and prevent cascading failures in distributed systems. Keep practicing to build even more resilient applications!

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

บทเรียน “การใช้ Fallback และ Timeout” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การใช้ Fallback และ Timeout” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Microservices & REST APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การใช้ Fallback และ Timeout”

กำหนดค่า fallback และ timeout ที่รองรับความผิดพลาดอย่างเหมาะสมสำหรับการเรียกบริการที่ไม่น่าเชื่อถือ คุณปฏิบัติ Spring Boot 4 Microservices & REST APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Microservices & REST APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Microservices & REST APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน

บทเรียน “การใช้ Fallback และ Timeout” ใช้เวลานานแค่ไหน

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

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Microservices & REST APIs นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Microservices & REST APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. Circuit Breaker ด้วย Resilience4j
  2. การใช้ Fallback และ Timeout
  3. การติดตามแบบกระจายด้วย Zipkin
← กลับไปที่ Spring Boot 4 Microservices & REST APIs