상태 점검 및 복원력 패턴
장애를 견디는 시스템을 위해 견고한 상태 점검을 설계하고 회로 차단기를 구현하며 다양한 복원력 패턴을 적용합니다.
상태 점검 및 복원력 패턴은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Complete Guide 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Introduction to Health Checks
In production, applications need to be robust. Health checks are automated ways to verify if an application or service is running correctly and ready to receive traffic.
- They tell orchestrators (like Kubernetes) if your app is alive.
- They prevent traffic from being sent to unhealthy instances.
- They help in automatic recovery and scaling decisions.
Spring Boot Actuator Health
Spring Boot Actuator provides a built-in /actuator/health endpoint. By default, it aggregates health information from various components like databases, disk space, and more.
When accessed, it returns a status, typically UP or DOWN, along with details about included components.
Accessing Health Endpoint
To see the health status, you just need to enable Actuator and access the endpoint. Here's how you might configure it in application.properties:
management.endpoints.web.exposure.include=health
management.endpoint.health.show-details=alwaysCustom Health Indicators
Sometimes, the default health checks aren't enough. You might have an external API, a custom cache, or a specific business logic that needs monitoring.
You can create custom health indicators by implementing the HealthIndicator interface to add your own checks to the /actuator/health endpoint.
Implementing a Custom Indicator
Let's create a simple custom health indicator for a hypothetical external service. If the service is 'available', it reports UP; otherwise, DOWN.
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class ExternalServiceHealthIndicator implements HealthIndicator {
private final String SERVICE_NAME = "MyExternalService";
@Override
public Health health() {
if (isExternalServiceUp()) {
return Health.up().withDetail(SERVICE_NAME, "Available").build();
} else {
return Health.down().withDetail(SERVICE_NAME, "Not Available").build();
}
}
private boolean isExternalServiceUp() {
// Simulate checking external service status
// In a real app, this would involve network calls, DB queries, etc.
return Math.random() > 0.3; // 70% chance of being up
}
public static void main(String[] args) {
ExternalServiceHealthIndicator indicator = new ExternalServiceHealthIndicator();
System.out.println("Service Health: " + indicator.health().getStatus());
}
}Liveness vs. Readiness Probes
When deploying to container orchestrators like Kubernetes, two types of probes are crucial:
- Liveness Probe: Determines if an application instance is running. If it fails, Kubernetes restarts the container.
- Readiness Probe: Determines if an application instance is ready to serve traffic. If it fails, Kubernetes stops sending traffic to it.
Spring Boot 2.3+ introduced distinct health groups for these, often mapped to /actuator/health/liveness and /actuator/health/readiness.
Introduction to Resilience
Even with health checks, external dependencies can fail, causing your application to crash or slow down. Resilience patterns help your application gracefully handle failures and continue operating under adverse conditions.
- They improve fault tolerance and stability.
- They prevent cascading failures across services.
- They ensure a better user experience even when parts of the system are struggling.
The Circuit Breaker Pattern
The Circuit Breaker pattern prevents an application from repeatedly trying to execute an operation that is likely to fail. It's like an electrical circuit breaker: if too much current flows, it trips to prevent damage.
- CLOSED: Requests pass through. If failures exceed a threshold, it trips to OPEN.
- OPEN: Requests immediately fail (fast-fail). After a timeout, it transitions to HALF_OPEN.
- HALF_OPEN: A limited number of test requests are allowed. If they succeed, it closes; otherwise, it opens again.
Circuit Breaker with Resilience4j
Resilience4j is a popular library for implementing resilience patterns. Here's a simplified example of a circuit breaker protecting a slow method call.
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import java.time.Duration;
public class CircuitBreakerDemo {
private final CircuitBreaker circuitBreaker;
public CircuitBreakerDemo() {
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.failureRateThreshold(50) // 50% failure rate to open
.waitDurationInOpenState(Duration.ofSeconds(5)) // 5s before HALF_OPEN
.ringBufferSizeInHalfOpenState(2) // 2 calls in HALF_OPEN
.ringBufferSizeInClosedState(5) // 5 calls in CLOSED for failure rate calc
.build();
CircuitBreakerRegistry circuitBreakerRegistry =
CircuitBreakerRegistry.of(circuitBreakerConfig);
circuitBreaker = circuitBreakerRegistry.circuitBreaker("myService");
}
public String callExternalService() {
return circuitBreaker.executeSupplier(() -> {
if (Math.random() < 0.6) { // Simulate 60% failure rate
throw new RuntimeException("Service failed!");
}
return "Service Data";
});
}
public static void main(String[] args) {
CircuitBreakerDemo demo = new CircuitBreakerDemo();
for (int i = 0; i < 15; i++) {
try {
System.out.println(i + ": " + demo.callExternalService());
} catch (Exception e) {
System.err.println(i + ": Error - " + e.getMessage() +
" | CB State: " + demo.circuitBreaker.getState());
try { Thread.sleep(500); } catch (InterruptedException ie) {}
}
}
}
}Fallback Methods
When a circuit breaker is open or a service call fails, you don't always want to just throw an error. A fallback method provides an alternative response or action when the primary operation fails.
This allows your application to degrade gracefully, perhaps by returning cached data, a default response, or an empty list, instead of crashing or showing a full error page.
Quick Check on Resilience
Which of the following are benefits of implementing resilience patterns like the Circuit Breaker?
Recap: Health & Resilience
We've explored how health checks, particularly with Spring Boot Actuator and custom indicators, help monitor application status and readiness for traffic.
We also learned about resilience patterns, focusing on the Circuit Breaker, to prevent cascading failures and ensure graceful degradation when external services or components fail. Implementing these patterns is key for building robust, production-ready microservices.
자주 묻는 질문
“상태 점검 및 복원력 패턴” 강의는 무료인가요?
네 — “상태 점검 및 복원력 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.
“상태 점검 및 복원력 패턴”에서 뭘 배우나요?
장애를 견디는 시스템을 위해 견고한 상태 점검을 설계하고 회로 차단기를 구현하며 다양한 복원력 패턴을 적용합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“상태 점검 및 복원력 패턴” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.