서비스 호출에 통합하기
외부 서비스 호출을 감싸고 장애를 방지하도록 회로 차단기를 마이크로서비스에 통합합니다.
서비스 호출에 통합하기은(는) CoddyKit의 무료 Microservices Communication Patterns (Saga, Circuit Breaker) 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Microservices Communication Patterns (Saga, Circuit Breaker) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Microservices Communication Patterns (Saga, Circuit Breaker) 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Wrap Up Your Calls!
Welcome to the final lesson on implementing Circuit Breakers! Today, we'll get hands-on and learn how to integrate a circuit breaker directly into your microservice's external calls.
Protecting these calls is crucial for building resilient systems that can gracefully handle failures and maintain responsiveness, even when dependencies are struggling.
Direct Service Calls
Imagine your service needs data from another microservice. A common way to do this is a direct method call or HTTP request. But what happens if that external service is slow or down?
Let's look at a basic setup without any protection.
import java.util.concurrent.ThreadLocalRandom;
class ExternalService {
public String getData() throws Exception {
System.out.println("ExternalService: Attempting to get data...");
// Simulate success for now
return "Data from external service";
}
}
public class Main {
public static void main(String[] args) {
ExternalService service = new ExternalService();
try {
String result = service.getData();
System.out.println("Result: " + result);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}Simulating Service Failure
In the real world, external services aren't always perfect. They can fail due to network issues, overload, or bugs. Let's update our ExternalService to simulate these failures randomly.
Run the code a few times. You'll see how a single failure can break our Main application.
import java.util.concurrent.ThreadLocalRandom;
class ExternalService {
private int callCount = 0;
public String getData() throws Exception {
callCount++;
System.out.println("ExternalService: Call #" + callCount);
// Simulate failure 50% of the time
if (ThreadLocalRandom.current().nextDouble() < 0.5) {
throw new RuntimeException("Simulated External Service Failure!");
}
return "Data from external service (call #" + callCount + ")";
}
}
public class Main {
public static void main(String[] args) {
ExternalService service = new ExternalService();
for (int i = 0; i < 3; i++) {
System.out.println("--- Attempt " + (i + 1) + " ---");
try {
String result = service.getData();
System.out.println("Result: " + result);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.println();
try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}
}The Circuit Breaker Wrapper
This is where the Circuit Breaker comes in! Instead of calling the external service directly, we 'wrap' the call with our circuit breaker.
The circuit breaker then manages the call, decides if it should even be attempted (if the circuit is open), and handles failures. Here's a very simplified version of how such a wrapper might look:
import java.util.concurrent.Callable;
class MyCircuitBreaker {
// In a real CB, this would manage state (open, closed, half-open)
// and apply thresholds. For this lesson, we focus on the integration.
public <T> T execute(Callable<T> primaryCall) throws Exception {
try {
System.out.println("CB: Executing primary call...");
return primaryCall.call(); // Attempt the actual service call
} catch (Exception e) {
// A real CB would update its state here (e.g., trip the circuit)
System.err.println("CB: Primary call failed: " + e.getMessage());
throw e; // Re-throw for now, we'll add fallback later
}
}
}Basic CB Integration
Now let's use our basic MyCircuitBreaker to wrap the calls to our unreliable ExternalService. Notice how the Main method now uses the circuit breaker's execute method.
Run this code. While it still shows errors, the circuit breaker is now involved in mediating the calls.
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
// --- MyCircuitBreaker (Simplified) ---
class MyCircuitBreaker {
public <T> T execute(Callable<T> primaryCall) throws Exception {
try {
System.out.println("CB: Executing primary call...");
return primaryCall.call();
} catch (Exception e) {
System.err.println("CB: Primary call failed: " + e.getMessage());
throw e;
}
}
}
// --- ExternalService (from previous scene) ---
class ExternalService {
private int callCount = 0;
public String getData() throws Exception {
callCount++;
System.out.println("ExternalService: Call #" + callCount);
if (ThreadLocalRandom.current().nextDouble() < 0.5) {
throw new RuntimeException("Simulated External Service Failure!");
}
return "Data from external service (call #" + callCount + ")";
}
}
// --- Main Application ---
public class Main {
public static void main(String[] args) {
ExternalService service = new ExternalService();
MyCircuitBreaker circuitBreaker = new MyCircuitBreaker();
for (int i = 0; i < 3; i++) {
System.out.println("--- Attempt " + (i + 1) + " ---");
try {
String result = circuitBreaker.execute(
() -> service.getData() // The operation to protect
);
System.out.println("Result: " + result);
} catch (Exception e) {
System.err.println("Main: Caught error after CB: " + e.getMessage());
}
System.out.println();
try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}
}Graceful Failure: Fallbacks
Catching errors is good, but what if we could provide a default or alternative response when the primary service call fails or the circuit is open? This is where fallbacks come in.
- A fallback is a predefined action or value that gets returned when the main operation cannot complete successfully.
- It helps maintain a good user experience by preventing total outages and providing partial functionality.
- Think of it as a 'plan B' for your service calls.
Implementing Fallback Logic
We'll enhance our MyCircuitBreaker to accept a second Callable: the fallback operation. If the primaryCall fails, the fallbackCall will be executed instead.
This makes our circuit breaker much more useful for handling failures gracefully.
import java.util.concurrent.Callable;
class MyCircuitBreaker {
public <T> T execute(Callable<T> primaryCall, Callable<T> fallbackCall) {
try {
System.out.println("CB: Executing primary call...");
return primaryCall.call();
} catch (Exception e) {
System.err.println("CB: Primary call failed. Invoking fallback: " + e.getMessage());
try {
// If primary fails, invoke the fallback
return fallbackCall.call();
} catch (Exception fallbackE) {
System.err.println("CB: Fallback call also failed: " + fallbackE.getMessage());
return null; // Or throw a specific exception if fallback is critical
}
}
}
}Putting It All Together
Now, let's see the full picture. We'll use our updated MyCircuitBreaker with both the primary service call and a simple fallback message.
Run this code multiple times. When the ExternalService fails, you'll now get the fallback message instead of an error in your Main application!
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
// --- MyCircuitBreaker (with Fallback) ---
class MyCircuitBreaker {
public <T> T execute(Callable<T> primaryCall, Callable<T> fallbackCall) {
try {
System.out.println("CB: Executing primary call...");
return primaryCall.call();
} catch (Exception e) {
System.err.println("CB: Primary call failed. Invoking fallback: " + e.getMessage());
try {
return fallbackCall.call();
} catch (Exception fallbackE) {
System.err.println("CB: Fallback call also failed: " + fallbackE.getMessage());
return null;
}
}
}
}
// --- ExternalService (with failures) ---
class ExternalService {
private int callCount = 0;
public String getData() throws Exception {
callCount++;
System.out.println("ExternalService: Call #" + callCount);
if (ThreadLocalRandom.current().nextDouble() < 0.5) {
throw new RuntimeException("Simulated External Service Failure!");
}
return "Data from external service (call #" + callCount + ")";
}
}
// --- Main Application ---
public class Main {
public static void main(String[] args) {
ExternalService service = new ExternalService();
MyCircuitBreaker circuitBreaker = new MyCircuitBreaker();
System.out.println("Attempting to fetch data with Circuit Breaker and Fallback:");
for (int i = 0; i < 5; i++) {
System.out.println("--- Attempt " + (i + 1) + " ---");
String result = circuitBreaker.execute(
() -> service.getData(), // Primary operation
() -> "Fallback: Service is currently unavailable." // Fallback operation
);
System.out.println("Result: " + result);
System.out.println();
try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}
}Strategic Integration Points
Where exactly should you place circuit breakers in your architecture?
- Service Clients: Wrap all calls made from your service to other external services. This is the most common place.
- API Gateways: If you use an an API Gateway, it's an excellent place to implement circuit breakers for calls to downstream microservices, protecting your frontend from direct service failures.
- Dedicated Proxy Layers: For very complex systems, a dedicated proxy or sidecar pattern can manage circuit breakers transparently for all outbound calls.
Integrating Circuit Breakers
You've learned how to wrap external service calls with a Circuit Breaker. Let's check your understanding.
Lesson Summary
Great job! In this lesson, you've learned the practical steps of integrating a circuit breaker into your microservice calls. We covered:
- The risks of unprotected external service calls.
- How to 'wrap' a service call using a circuit breaker's
executemethod. - The importance and implementation of fallback operations for graceful degradation.
- Common strategic points in your architecture for integrating circuit breakers.
By applying these techniques, you can significantly enhance the resilience and stability of your distributed systems. Keep practicing!
자주 묻는 질문
“서비스 호출에 통합하기” 강의는 무료인가요?
네 — “서비스 호출에 통합하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Microservices Communication Patterns (Saga, Circuit Breaker) 강의 전체를 잠금 해제할 수 있습니다. Microservices Communication Patterns (Saga, Circuit Breaker) 강의에는 총 4개의 강의가 포함되어 있습니다.
“서비스 호출에 통합하기”에서 뭘 배우나요?
외부 서비스 호출을 감싸고 장애를 방지하도록 회로 차단기를 마이크로서비스에 통합합니다. 브라우저에서 직접 실행하는 실습 코드로 Microservices Communication Patterns (Saga, Circuit Breaker)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Microservices Communication Patterns (Saga, Circuit Breaker)을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Microservices Communication Patterns (Saga, Circuit Breaker)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“서비스 호출에 통합하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Microservices Communication Patterns (Saga, Circuit Breaker) 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Microservices Communication Patterns (Saga, Circuit Breaker) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 회로 차단기 라이브러리 선택
- 회로 차단기 인스턴스 구성
- 서비스 호출에 통합하기
- 회로 차단기에 대체 처리 추가