在 javascript 中实现请求重试与熔断,核心做法是封装一个异步函数,利用递归或循环配合指数退避算法处理重试逻辑,并引入状态机或计数器来管理熔断器的开启、关闭和半开状态。具体实现时,需设置最大重试次数、基础延迟时间以及熔断阈值(如连续失败次数),当失败次数达到阈值时触发熔断,阻断后续请求;熔断一段时间后自动进入半开状态试探性放行一次请求,若成功则重置计数器恢复服务,若失败则重新进入熔断状态。

如何配置重试策略以应对临时网络波动
针对临时网络波动,应配置基于指数退避的重试策略,即每次重试的等待时间随重试次数呈指数级增长,以避免对服务器造成瞬时压力。具体做法是在重试循环中计算当前延迟为 baseDelay * Math.pow(2, retryCount),并加入随机抖动(Jitter)防止雪崩效应。同时,必须区分可重试的错误(如网络超时、503 Service Unavailable)和不可重试的错误(如404 Not Found、401 Unauthorized),仅对前者执行重试。

function exponentialBackoffRetry(url, options = {}) {
const { maxRetries = 3, baseDelay = 1000 } = options;
let attempt = 0;
async function execute() {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
attempt++;
if (attempt >= maxRetries) throw error;
// 指数退避 + 随机抖动
const delay = baseDelay * Math.pow(2, attempt - 1) + Math.random() * 1000;
console.log(`Retry ${attempt}/${maxRetries} after ${delay}ms`);
await new Promise(r => setTimeout(r, delay));
return execute();
}
}
return execute();
}
// 使用示例
exponentialBackoffRetry('https://api.example.com/data')
.then(data => console.log('Success:', data))
.catch(err => console.error('Failed:', err));
如何实现熔断器以防止级联故障
为防止级联故障,需实现一个熔断器中间件,监控连续失败次数。当连续失败次数超过设定阈值(如 circuitBreakerThreshold)时,熔断器进入 OPEN 状态,此时所有新请求直接抛出异常而不发起实际网络调用。经过一段冷却时间(cooldownPeriod)后,熔断器进入 HALF_OPEN 状态,允许少量试探性请求通过。如果试探请求成功,熔断器重置为 CLOSED 状态并恢复正常流量;如果失败,则再次进入 OPEN 状态并重置冷却计时器。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
立即学习“Java免费学习笔记(深入)”;

class CircuitBreaker {
constructor(options = {}) {
this.threshold = options.threshold || 5;
this.cooldown = options.cooldown || 60000;
this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
this.failureCount = 0;
this.lastFailureTime = null;
}
async execute(fn) {
if (this.state === 'OPEN') {
if (Date.now() - this.lastFailureTime > this.cooldown) {
this.state = 'HALF_OPEN';
console.log('Circuit Breaker: Half-Open');
} else {
throw new Error('Circuit Breaker: Open');
}
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
onSuccess() {
this.failureCount = 0;
this.state = 'CLOSED';
console.log('Circuit Breaker: Closed');
}
onFailure() {
this.failureCount++;
this.lastFailureTime = Date.now();
if (this.failureCount >= this.threshold) {
this.state = 'OPEN';
console.log('Circuit Breaker: Opened due to failures');
}
}
}
// 集成重试与熔断
const breaker = new CircuitBreaker({ threshold: 3, cooldown: 5000 });
async function safeFetch(url) {
return breaker.execute(() => exponentialBackoffRetry(url));
}
safeFetch('https://unstable-api.com/data')
.then(console.log)
.catch(e => console.error(e.message));
熔断器在半开状态下试探请求失败会怎样
当熔断器处于 HALF_OPEN 状态时,系统允许单个或少数几个请求通过以测试后端是否恢复。如果这个试探性请求失败,熔断器会立即重新进入 OPEN 状态,并将 lastFailureTime 更新为当前时间,从而重置冷却期。这意味着即使之前已经等待了部分冷却时间,一旦试探失败,客户端仍需等待完整的 cooldown 时间后才能再次尝试进入半开状态。这种机制确保了在后端尚未完全稳定时,不会过早地大量涌入请求导致二次冲击。

















