实现说明
逻辑集中在类 CircuitBreaker、State和函数 main里。
常见问题
「手写熔断器状态机(Java)」这个示例怎么运行?
文件自包含:直接运行,没有需要预先安装的依赖。
核心语句
return "opened after " + failures + " failures";
return "failed " + failures + "/" + threshold;
return "fast-fail (open)";
代码示例
public class CircuitBreaker {
enum State { CLOSED, OPEN }
private State state = State.CLOSED;
private int failures = 0;
private final int threshold;
CircuitBreaker(int threshold) { this.threshold = threshold; }
// 熔断语义:CLOSED 放行并统计连续失败,达到阈值翻到 OPEN 快速失败
String call(boolean upstreamHealthy) {
if (state == State.OPEN) {
return "fast-fail (open)";
}
if (upstreamHealthy) {
failures = 0;
state = State.CLOSED;
return "ok";
}
if (++failures >= threshold) {
state = State.OPEN;
return "opened after " + failures + " failures";
}
return "failed " + failures + "/" + threshold;
}
public static void main(String[] args) {
CircuitBreaker breaker = new CircuitBreaker(3);
System.out.println(breaker.call(false)); // failed 1/3
System.out.println(breaker.call(false)); // failed 2/3
System.out.println(breaker.call(false)); // opened after 3 failures
System.out.println(breaker.call(false)); // fast-fail (open)
System.out.println(breaker.call(true)); // 仍 fast-fail:不再打到上游
}
}