대체 처리와 시간 제한 구현하기
신뢰할 수 없는 서비스 호출에 대비해 우아한 대체 처리와 시간 제한을 구성합니다.
대체 처리와 시간 제한 구현하기은(는) CoddyKit의 무료 Spring Boot 4 Microservices & REST APIs 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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!
자주 묻는 질문
“대체 처리와 시간 제한 구현하기” 강의는 무료인가요?
네 — “대체 처리와 시간 제한 구현하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Microservices & REST APIs 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 3개의 강의가 포함되어 있습니다.
“대체 처리와 시간 제한 구현하기”에서 뭘 배우나요?
신뢰할 수 없는 서비스 호출에 대비해 우아한 대체 처리와 시간 제한을 구성합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Microservices & REST APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Microservices & REST APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.
“대체 처리와 시간 제한 구현하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Microservices & REST APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Microservices & REST APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Resilience4j를 사용한 회로 차단기
- 대체 처리와 시간 제한 구현하기
- Zipkin을 사용한 분산 추적