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

熔断器与舱壁模式

学习如何将熔断器与舱壁模式结合使用,隔离资源故障并防止问题级联。

熔断器与舱壁模式 是 CoddyKit 上的免费 Microservices Communication Patterns (Saga, Circuit Breaker) 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Microservices Communication Patterns (Saga, Circuit Breaker) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Microservices Communication Patterns (Saga, Circuit Breaker) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Patterns Work Better Together

Resilience patterns like Circuit Breaker and Bulkhead are powerful on their own. But in complex microservices, combining them offers even stronger protection.

Think of it like different layers of security for your application. Each layer catches different types of threats, creating a more robust defense.

Circuit Breaker Refresher

Remember the Circuit Breaker pattern? It's like an electrical circuit for your service calls.

  • It monitors calls to a service.
  • If failures exceed a threshold, it 'opens' the circuit.
  • Once open, further calls fail immediately, preventing overload to the failing service and saving resources.
  • After a timeout, it 'half-opens' to test if the service has recovered.

Bulkhead Pattern Refresher

The Bulkhead pattern isolates resources. Imagine a ship with watertight compartments (bulkheads).

  • If one compartment floods, the others remain safe.
  • In microservices, this means separating resource pools (e.g., thread pools, connections) for different services.
  • A failure in one service's resource pool won't exhaust resources needed by other services.

Synergy: CB + Bulkhead

Why use both? They tackle different problems but complement each other perfectly.

  • Circuit Breaker: Focuses on stopping requests to a failing service.
  • Bulkhead: Focuses on isolating resources to prevent cascading failures due to resource exhaustion.

Together, they provide a comprehensive defense against various failure modes.

Bulkhead Helps Circuit Breaker

How does Bulkhead make Circuit Breaker better?

A Circuit Breaker needs to detect failures. If a service is overwhelmed (e.g., due to resource exhaustion) and all calls to it start failing slowly, it can take time for the Circuit Breaker to open.

By isolating resources, Bulkhead ensures that only a limited set of resources is consumed by a misbehaving service, preventing total exhaustion and allowing the Circuit Breaker to react more quickly and cleanly to actual service failures, rather than just resource starvation.

Circuit Breaker Helps Bulkhead

And how does Circuit Breaker enhance Bulkhead?

If a service is known to be failing (Circuit Breaker is OPEN), the Circuit Breaker will intercept requests and fail them immediately, before they even try to acquire a resource from the Bulkhead's pool.

This means the Bulkhead's limited resources are not wasted on calls destined to fail anyway, preserving them for other, potentially healthy, operations or for when the service recovers.

Real-World: Thread Pools

A common way to implement the Bulkhead pattern is using thread pools.

  • Assign a dedicated, limited thread pool to calls for a specific external service.
  • If that service is slow or unresponsive, only its dedicated threads get tied up.
  • Other services, with their own thread pools, remain unaffected.

When combined with a Circuit Breaker, the CB stops calls before they even enter the thread pool if the service is down.

Code: CB & BH in Action

This example shows how a Circuit Breaker (CB) check happens before a Bulkhead (BH) resource acquisition. If the CB is open, the call fails immediately, saving BH resources.

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main {
    private static AtomicBoolean circuitOpen = new AtomicBoolean(false);
    private static long lastFailureTime = 0;
    private static final long RESET_TIMEOUT_MS = 5000;

    private static final Semaphore serviceBulkhead = new Semaphore(2);

    public static void callProtectedService(String callerId) {
        // 1. Circuit Breaker check (Fail Fast)
        if (circuitOpen.get()) {
            if (System.currentTimeMillis() - lastFailureTime > RESET_TIMEOUT_MS) {
                System.out.println(callerId + ": Circuit Half-Open. Testing service...");
                circuitOpen.set(false); // Simple reset for demo
            } else {
                System.out.println(callerId + ": CB OPEN. REJECTED!");
                return;
            }
        }

        // 2. Bulkhead check (Resource Isolation)
        boolean acquiredBulkhead = false;
        try {
            if (serviceBulkhead.tryAcquire()) {
                acquiredBulkhead = true;
                System.out.println(callerId + ": BH slot ACQUIRED. Calling...");
                Thread.sleep(200); // Simulate work

                if (callerId.equals("Call-3") || callerId.equals("Call-4")) {
                    System.out.println(callerId + ": Simulating FAILURE!");
                    circuitOpen.set(true);
                    lastFailureTime = System.currentTimeMillis();
                } else {
                    System.out.println(callerId + ": Call SUCCESS.");
                }
            } else {
                System.out.println(callerId + ": BH FULL. REJECTED!");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println(callerId + ": Call interrupted.");
        } finally {
            if (acquiredBulkhead) {
                serviceBulkhead.release();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("--- First calls (CB CLOSED) ---");
        for (int i = 1; i <= 5; i++) {
            final int callNum = i;
            new Thread(() -> callProtectedService("Call-" + callNum)).start();
            Thread.sleep(50);
        }
        Thread.sleep(1500);

        System.out.println("\n--- Second calls (CB potentially OPEN) ---");
        for (int i = 6; i <= 10; i++) {
            final int callNum = i;
            new Thread(() -> callProtectedService("Call-" + callNum)).start();
            Thread.sleep(50);
        }
        Thread.sleep(6000);

        System.out.println("\n--- Third calls (after reset) ---");
        for (int i = 11; i <= 13; i++) {
            final int callNum = i;
            new Thread(() -> callProtectedService("Call-" + callNum)).start();
            Thread.sleep(50);
        }
    }
}

Combined Benefits

Using Circuit Breaker and Bulkhead together provides:

  • Enhanced Fault Isolation: Prevents a single failing service from taking down others, both by stopping calls and by limiting resource usage.
  • Improved Resource Management: Efficiently uses available resources, rejecting calls early if a service is known to be unhealthy.
  • Faster Recovery: Allows healthy parts of the system to continue functioning, aiding overall system stability and recovery.
  • Predictable Behavior: Helps maintain predictable response times and throughput under stress.

Quick Check

Which of the following statements accurately describe the benefits of combining the Circuit Breaker and Bulkhead patterns?

Recap: Stronger Together

In this lesson, we explored the powerful combination of the Circuit Breaker and Bulkhead patterns.

  • We saw how Circuit Breaker prevents calls to failing services.
  • We revisited how Bulkhead isolates resources.
  • Most importantly, we learned how they mutually enhance each other to create a more resilient and stable microservices architecture.

Next, we'll see how Circuit Breakers can be combined with Retry Logic for even more robust error handling!

常见问题解答

「熔断器与舱壁模式」课时是免费的吗?

是的 — 「熔断器与舱壁模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 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) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 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)