0Pricing
Microservices Communication Patterns (Saga, Circuit Breaker) · 课时

集成到服务调用中

将熔断器集成到微服务中,封装外部服务调用并防止故障扩散。

集成到服务调用中 是 CoddyKit 上的免费 Microservices Communication Patterns (Saga, Circuit Breaker) 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 execute method.
  • 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!

常见问题解答

「集成到服务调用中」课时是免费的吗?

是的 — 「集成到服务调用中」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Microservices Communication Patterns (Saga, Circuit Breaker) 课程的其余内容,请升级到 CoddyKit PRO。 Microservices Communication Patterns (Saga, Circuit Breaker) 课程共包含 4 节课。

「集成到服务调用中」这节课中我会学到什么?

将熔断器集成到微服务中,封装外部服务调用并防止故障扩散。 你通过在浏览器中直接运行的动手代码来练习 Microservices Communication Patterns (Saga, Circuit Breaker),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Microservices Communication Patterns (Saga, Circuit Breaker) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Microservices Communication Patterns (Saga, Circuit Breaker) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「集成到服务调用中」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Microservices Communication Patterns (Saga, Circuit Breaker) 课中编写并运行代码吗?

能。每节 Microservices Communication Patterns (Saga, Circuit Breaker) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 选择熔断器库
  2. 配置熔断器实例
  3. 集成到服务调用中
  4. 为熔断器添加降级方案
← 返回 Microservices Communication Patterns (Saga, Circuit Breaker)