使用 opossum 实现熔断器,并监控 open/close/half-open 状态变化
解读
国内一线/二线互联网公司面试中,熔断器是“高可用”必考题。面试官不仅想看你会不会“用”,更关注:
- 是否理解三种状态迁移的触发条件与业务意义;
- 能否把状态变化实时透出,供告警、日志、网关二次决策;
- 是否能在 Node.js 单线程模型下避免“假死”或“惊群”;
- 代码是否可插拔、可测试、可灰度。
因此,答题时要给出“可运行、可观测、可灰度”的完整闭环,而非简单打印 console.log。
知识点
- opossum 核心选项:timeout、errorThresholdPercentage、resetTimeout、volumeThreshold;
- 状态机:CLOSED → OPEN → HALF_OPEN → CLOSED(或回到 OPEN);
- 事件:open、close、halfOpen、fire、fallback、success、failure、timeout;
- 指标透出:Prometheus + @opossum/prometheus 插件,或自定义 EventEmitter 推送到日志/消息队列;
- 线程安全:Node.js 单线程事件循环,熔断器状态变量无需锁,但要避免同步阻塞;
- 灰度发布:结合 launch-darkly 或自研配置中心,动态热更新 options;
- 测试策略:nock 模拟下游 5xx,sinon 做时间旅行(tick)验证 HALF_OPEN 恢复。
答案
以下示例基于 Egg.js(国内最常用企业级框架),可零改动移植到 NestJS、Midway、纯 Koa。
// app/lib/circuit.js
'use strict';
const CircuitBreaker = require('opossum');
const EventEmitter = require('events');
const promClient = require('prom-client');
// 全局注册,方便多数据源复用
const breakerState = new promClient.Gauge({
name: 'nodejs_circuit_breaker_state',
help: '0=closed, 1=open, 2=half_open',
labelNames: ['name'],
});
class ObservableBreaker extends EventEmitter {
constructor(name, asyncFn, options = {}) {
super();
this.name = name;
this.breaker = new CircuitBreaker(asyncFn, {
timeout: 3000, // 超过 3s 视为失败
errorThresholdPercentage: 60, // 60% 错误率触发熔断
resetTimeout: 30 * 1000, // 30s 后进入 half_open
volumeThreshold: 10, // 最少 10 次采样才统计
...options,
});
this._attachListeners();
}
_attachListeners() {
const b = this.breaker;
b.on('open', () => {
breakerState.set({ name: this.name }, 1);
this.emit('circuit_open', { name: this.name, at: Date.now() });
});
b.on('halfOpen', () => {
breakerState.set({ name: this.name }, 2);
this.emit('circuit_half_open', { name: this.name, at: Date.now() });
});
b.on('close', () => {
breakerState.set({ name: this.name }, 0);
this.emit('circuit_close', { name: this.name, at: Date.now() });
});
// 可选:记录 success/failure 用于告警
b.on('success', res => this.emit('success', res));
b.on('failure', err => this.emit('failure', err));
}
// 代理调用,保持 API 一致
async call(...args) {
return this.breaker.fire(...args);
}
// 热更新配置,生产环境通过配置中心触发
hotUpdate(options) {
this.breaker.options.resetTimeout = options.resetTimeout ?? this.breaker.options.resetTimeout;
this.breaker.options.errorThresholdPercentage = options.errorThresholdPercentage ?? this.breaker.options.errorThresholdPercentage;
}
// 健康检查接口透出状态
status() {
return {
name: this.name,
state: this.breaker.status.stats.opened ? 'open' :
this.breaker.status.stats.halfOpen ? 'half_open' : 'closed',
failures: this.breaker.stats.failures,
successes: this.breaker.stats.successes,
fallbacks: this.breaker.stats.fallbacks,
};
}
}
module.exports = ObservableBreaker;
使用层(Service):
// app/service/user.js
const ObservableBreaker = require('../lib/circuit');
const httpClient = require('urllib');
// 原始异步函数
async function fetchUserFromRpc(id) {
const { data } = await httpClient.request(`http://user-rpc.internal/v1/user/${id}`, {
dataType: 'json',
timeout: 3000,
});
return data;
}
// 熔断器实例,全局单例
const userBreaker = new ObservableBreaker('userRpc', fetchUserFromRpc, {
errorThresholdPercentage: 50,
resetTimeout: 15 * 1000,
});
// 监听状态变化,推送到日志 & 钉钉群
userBreaker.on('circuit_open', ({ name, at }) => {
console.error(`[${new Date(at).toLocaleString()}] 熔断器<${name}>已打开`);
// 可调用钉钉机器人告警
});
userBreaker.on('circuit_close', ({ name, at }) => {
console.log(`[${new Date(at).toLocaleString()}] 熔断器<${name}>已关闭`);
});
module.exports = app => ({
async getUser(id) {
try {
return await userBreaker.call(id);
} catch (e) {
// 统一降级:返回本地缓存或默认头像
app.logger.warn(`user rpc 熔断或异常,降级处理: ${e.message}`);
return { id, name: '默认用户', avatar: 'https://cdn.xxx.com/default.png' };
}
},
});
路由暴露指标:
// app/router.js
module.exports = app => {
app.get('/metrics', async ctx => {
ctx.set('Content-Type', promClient.register.contentType);
ctx.body = await promClient.register.metrics();
});
app.get('/health/circuit', ctx => {
ctx.body = [ app.service.user.breaker.status() ];
});
};
单元测试(mocha + sinon + nock):
// test/service/user.test.js
const nock = require('nock');
const sinon = require('sinon');
const { getUser } = require('../../app/service/user');
describe('用户服务熔断', () => {
afterEach(() => {
nock.cleanAll();
});
it('应触发 open 并在半开后恢复', async function() {
this.timeout(5000);
// 模拟 5 次 500
nock('http://user-rpc.internal')
.get(/\/v1\/user\/\d+/)
.times(5)
.reply(500, { message: 'error' });
// 连续失败
for (let i = 0; i < 5; i++) {
await getUser(i);
}
// 断言状态为 open
const status = global.app.service.user.breaker.status();
status.state.should.equal('open');
// 时间旅行 16s,进入 half_open
const clock = sinon.useFakeTimers(Date.now());
clock.tick(16 * 1000);
// 模拟一次成功
nock('http://user-rpc.internal')
.get('/v1/user/1')
.reply(200, { id: 1, name: 'ok' });
await getUser(1);
status.state.should.equal('closed');
clock.restore();
});
});
拓展思考
- 多维度熔断:按“接口 + 上游节点”粒度拆分 breaker,防止一个接口拖垮整个服务;
- 自适应策略:结合滑动窗口与 PID 算法,根据 RT 和错误率动态调整阈值,而非固定 60%;
- 双向熔断:不仅 consumer 熔断 provider,provider 也可基于负载主动推“背压”信号,配合 gRPC HTTP/2 GOAWAY;
- 与 Service Mesh 集成:Istio 自带 DestinationRule 熔断,Node.js 侧可降级为“最后一道保险”,避免双重重试;
- 状态持久化:将 open/close 事件写入 Redis Stream,再消费到 ELK,方便复盘;
- 前端感知:在 SSR 场景,把熔断状态注入 HTML,前端可提前渲染兜底骨架屏,提升体验;
- 混沌工程:用 ChaosBlade 随机注入 100 ms~2 s 延迟,验证 HALF_OPEN 阶段的成功率是否满足 SLO(≥99.5%)。