Resilience4j를 사용한 회로 차단기
마이크로서비스에서 장애가 연쇄적으로 확산되는 것을 막기 위해 Resilience4j로 회로 차단기 패턴을 적용합니다.
Resilience4j를 사용한 회로 차단기은(는) CoddyKit의 무료 Spring Boot 4 Microservices & REST APIs 강의입니다. 이것은 3개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Microservices & REST APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 3개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Building Resilient Microservices
Microservices are great, but they also bring new challenges. When one service fails, it shouldn't take down the whole system. This is where resilience comes in.
Building resilient systems means they can recover gracefully from failures and continue to function, even if in a degraded mode. It's crucial for maintaining service availability and user experience.
Avoiding Cascading Failures
Imagine a chain of services: Service A calls B, which calls C. If Service C becomes slow or unresponsive, Service B will wait, consuming resources. Then Service A will wait for B, and so on.
Eventually, all services in the chain might exhaust their resources (like threads or connections) and fail, leading to a complete system outage. This is a cascading failure, a common problem in distributed systems.
The Circuit Breaker Pattern
The circuit breaker pattern helps prevent cascading failures. It's like an electrical circuit breaker in your house: if there's an overload, it 'trips' and cuts off the power to prevent damage.
In software, a circuit breaker wraps a function call to a potentially failing service. If calls to that service repeatedly fail, the circuit breaker 'opens,' preventing further calls to the failing service and returning an error immediately.
Resilience4j: Our Tool
Resilience4j is a lightweight, easy-to-use fault-tolerance library for Java and Kotlin. It provides several patterns to make your applications more resilient, including:
- Circuit Breaker: Prevents repeated calls to failing services.
- Retry: Automatically retries failed operations.
- Rate Limiter: Controls the rate of requests to a service.
In this lesson, we'll focus specifically on the Circuit Breaker pattern.
Setup: Adding Dependency
First, let's add the necessary dependency to our Spring Boot project. For Maven, you'd add this to your pom.xml:
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot2</artifactId>
<version>2.2.0</version> <!-- Use latest stable -->
</dependency>
This dependency brings in the core Resilience4j modules and its Spring Boot integration for easy configuration.
Configuring Circuit Breaker
We can configure circuit breakers in our application.yml or application.properties. Here's a basic example for a service named 'myExternalService':
resilience4j.circuitbreaker:
instances:
myExternalService:
failureRateThreshold: 50
waitDurationInOpenState: 5s
slidingWindowType: COUNT_BASED
slidingWindowSize: 10
failureRateThreshold: If 50% of calls fail, the circuit opens.waitDurationInOpenState: How long the circuit stays open (5 seconds).slidingWindowType&slidingWindowSize: Metrics are collected over the last 10 calls.
Implementing Circuit Breaker
Now, let's protect a service call using the @CircuitBreaker annotation. This tells Spring to apply the configured circuit breaker named "myExternalService" to this method.
Try running this example. If callExternalService() throws an exception frequently (simulated here), the circuit will eventually open and reject calls immediately.
package com.coddykit.resilience;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
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 java.util.Random;
@SpringBootApplication
@RestController
public class CircuitBreakerDemoApplication {
private Random random = new Random();
public static void main(String[] args) {
SpringApplication.run(CircuitBreakerDemoApplication.class, args);
}
@GetMapping("/call-external")
@CircuitBreaker(name = "myExternalService")
public String callExternalService() {
System.out.println("Attempting external service call...");
if (random.nextBoolean()) { // Simulate 50% failure rate
System.out.println("External service failed!");
throw new RuntimeException("External Service Unavailable!");
}
System.out.println("External service call successful!");
return "External Service Data";
}
}Circuit Breaker States
A circuit breaker operates in three main states:
- CLOSED: Normal operation. Calls go through. If failures exceed a threshold, it transitions to OPEN.
- OPEN: Calls are immediately rejected with an error. After a
waitDurationInOpenState, it transitions to HALF_OPEN. - HALF_OPEN: A limited number of test calls are allowed through. If these succeed, it transitions back to CLOSED. If they fail, it returns to OPEN.
This cycle prevents overwhelming a struggling service while allowing it to recover.
Graceful Fallbacks
When a circuit breaker is OPEN, or if a call fails for other reasons, we don't want to just return a generic error. We can provide a fallback method to return a default response or perform alternative logic.
Resilience4j's @CircuitBreaker annotation allows you to specify a fallback method that will be called if the primary method fails or the circuit is open. This ensures a more graceful degradation of service.
Circuit Breaker with Fallback
Let's enhance our previous example with a fallback method. When the circuit is open or callExternalService() fails, fallbackMethod() will be executed instead.
Run this and try to trigger the circuit breaker. Notice how the fallback message is returned when the external service fails or the circuit is open, providing a better user experience.
package com.coddykit.resilience;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
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 java.util.Random;
@SpringBootApplication
@RestController
public class CircuitBreakerWithFallbackApplication {
private Random random = new Random();
public static void main(String[] args) {
SpringApplication.run(CircuitBreakerWithFallbackApplication.class, args);
}
@GetMapping("/call-external-with-fallback")
@CircuitBreaker(name = "myExternalService", fallbackMethod = "fallbackMethod")
public String callExternalService() {
System.out.println("Attempting external service call...");
if (random.nextBoolean()) { // Simulate 50% failure rate
System.out.println("External service failed!");
throw new RuntimeException("External Service Unavailable!");
}
System.out.println("External service call successful!");
return "External Service Data";
}
// The fallback method must have the same return type and can accept a Throwable parameter
public String fallbackMethod(Throwable t) {
System.out.println("Fallback method called: " + t.getMessage());
return "Fallback: Default Data (Service Currently Unavailable)";
}
}Circuit Breaker Check
Consider a circuit breaker configured with failureRateThreshold: 70 and slidingWindowSize: 10. If 8 out of the last 10 consecutive calls fail while the circuit is CLOSED, what is the most likely immediate next state of the circuit breaker?
Recap: Circuit Breakers
We've learned how circuit breakers, especially with Resilience4j, are vital for building resilient microservices. They prevent cascading failures by stopping repeated calls to failing services.
Key takeaways:
- Circuit breakers protect services from overload and unresponsiveness.
- They operate in CLOSED, OPEN, and HALF_OPEN states.
- Fallbacks provide graceful degradation when a service is unavailable.
Next, we'll explore other resilience patterns like implementing fallbacks and timeouts more deeply.
자주 묻는 질문
“Resilience4j를 사용한 회로 차단기” 강의는 무료인가요?
네 — “Resilience4j를 사용한 회로 차단기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Microservices & REST APIs 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 3개의 강의가 포함되어 있습니다.
“Resilience4j를 사용한 회로 차단기”에서 뭘 배우나요?
마이크로서비스에서 장애가 연쇄적으로 확산되는 것을 막기 위해 Resilience4j로 회로 차단기 패턴을 적용합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Microservices & REST APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Microservices & REST APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 1번째 강의입니다.
“Resilience4j를 사용한 회로 차단기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Microservices & REST APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Microservices & REST APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Resilience4j를 사용한 회로 차단기
- 대체 처리와 시간 제한 구현하기
- Zipkin을 사용한 분산 추적