PHpullh
학습 라이브러리/Java/서킷 브레이커 패턴

JAVA · 디자인패턴

서킷 브레이커 패턴

장애 전파를 차단하는 서킷 브레이커를 직접 구현합니다.

디자인패턴고급CircuitBreaker서킷브레이커장애허용Resilience

핵심 설명

장애 전파를 차단하는 서킷 브레이커를 직접 구현합니다.

Java code

import java.util.concurrent.atomic.*;
import java.util.function.Supplier;

public class CircuitBreaker {
    enum State { CLOSED, OPEN, HALF_OPEN }

    private final AtomicReference<State> state = new AtomicReference<>(State.CLOSED);
    private final AtomicInteger failureCount = new AtomicInteger(0);
    private final int threshold;
    private final long resetTimeout;
    private volatile long lastFailureTime;

    CircuitBreaker(int threshold, long resetTimeoutMs) {
        this.threshold = threshold;
        this.resetTimeout = resetTimeoutMs;
    }

    <T> T execute(Supplier<T> action, Supplier<T> fallback) {
        if (state.get() == State.OPEN) {
            if (System.currentTimeMillis() - lastFailureTime > resetTimeout) {
                state.set(State.HALF_OPEN);
            } else {
                System.out.println("[CB] OPEN - 폴백 실행");
                return fallback.get();
            }
        }
        try {
            T result = action.get();
            reset();
            return result;
        } catch (Exception e) {
            recordFailure();
            System.out.printf("[CB] 실패 %d/%d%n", failureCount.get(), threshold);
            return fallback.get();
        }
    }

    private void reset() {
        failureCount.set(0);
        state.set(State.CLOSED);
    }

    private void recordFailure() {
        int count = failureCount.incrementAndGet();
        lastFailureTime = System.currentTimeMillis();
        if (count >= threshold) {
            state.set(State.OPEN);
            System.out.println("[CB] 서킷 OPEN!");
        }
    }

    public static void main(String[] args) {
        CircuitBreaker cb = new CircuitBreaker(3, 5000);
        for (int i = 0; i < 5; i++) {
            String result = cb.execute(
                () -> { throw new RuntimeException("서버 장애"); },
                () -> "폴백 응답");
            System.out.println("결과: " + result);
        }
    }
}

학습 팁

CLOSED(정상) -> OPEN(차단) -> HALF_OPEN(시험)의 3가지 상태 전이를 이해하세요. Resilience4j 라이브러리가 프로덕션용으로 적합합니다.

주의할 점

HALF_OPEN 상태에서 동시 요청이 몰리면 서비스가 다시 과부하될 수 있습니다. 시험 요청 수를 제한하세요.

자주 묻는 질문

서킷 브레이커 패턴란 무엇인가요?

장애 전파를 차단하는 서킷 브레이커를 직접 구현합니다.

서킷 브레이커 패턴 학습 시 주의할 점은 무엇인가요?

HALF_OPEN 상태에서 동시 요청이 몰리면 서비스가 다시 과부하될 수 있습니다. 시험 요청 수를 제한하세요.

Continue Learning

Java 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.