构建具备重试、断路器和优雅降级的弹性 API 客户端和实时连接的常用模式。适用于生产系统处理故障。触发词:重试逻辑、断路器、连接弹性、指数退避、API 客户端、容错。
构建 API 客户端和实时连接, 以重试、 断路器和回落器优雅地处理故障是一项面向实际任务的技能,主要用于OpenClaw / Moltbot / Clawbot.;When to Use. building.。
从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;
若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。
构建具备容错能力的 API 客户端与实时连接,通过重试机制、熔断器和降级策略优雅地应对故障。
npx clawhub@latest install resilient-connections
interface RetryOptions {
maxRetries: number;
baseDelay: number;
maxDelay: number;
jitter?: boolean;
}
async function withRetry(
fn: () => Promise,
options: RetryOptions
): Promise {
const { maxRetries, baseDelay, maxDelay, jitter = true } = options;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxRetries) throw error;
// 使用指数退避计算延迟
let delay = Math.min(baseDelay * 2 ** attempt, maxDelay);
// 添加抖动(jitter),避免“惊群效应”(thundering herd)
if (jitter) {
delay = delay * (0.5 + Math.random());
}
await sleep(delay);
}
}
throw new Error('Unreachable');
}
// 使用示例
const data = await withRetry(
() => fetch('/api/data').then(r => r.json()),
{ maxRetries: 3, baseDelay: 1000, maxDelay: 30000 }
);
enum CircuitState {
Closed, // 正常运行状态
Open, // 故障中,拒绝请求
HalfOpen, // 尝试恢复,试探性放行请求
}
class CircuitBreaker {
private state = CircuitState.Closed;
private failures = 0;
private lastFailure = 0;
constructor(
private threshold: number = 5,
private timeout: number = 30000
) {}
async execute(fn: () => Promise): Promise {
if (this.state === CircuitState.Open) {
if (Date.now() - this.lastFailure > this.timeout) {
this.state = CircuitState.HalfOpen;
} else {
throw new Error('Circuit breaker is open');
}
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
private onSuccess() {
this.failures = 0;
this.state = CircuitState.Closed;
}
private onFailure() {
this.failures++;
this.lastFailure = Date.now();
if (this.failures >= this.threshold) {
this.state = CircuitState.Open;
}
}
}
interface FetchOptions extends RequestInit {
timeout?: number;
retries?: number;
}
async function resilientFetch(
url: string,
options: FetchOptions = {}
): Promise {
const { timeout = 10000, retries = 3, ...fetchOptions } = options;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
const fetchWithTimeout = async () => {
try {
const response = await fetch(url, {
...fetchOptions,
signal: controller.signal,
});
if (!response.ok && response.status >= 500) {
throw new Error(`Server error: ${response.status}`);
}
return response;
} finally {
clearTimeout(timeoutId);
}
};
return withRetry(fetchWithTimeout, {
maxRetries: retries,
baseDelay: 1000,
maxDelay: 10000,
});
}
class ReconnectingWebSocket {
private ws: WebSocket | null = null;
private retries = 0;
private maxRetries = 10;
constructor(
private url: string,
private onMessage: (data: unknown) => void
) {
this.connect();
}
private connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
this.retries = 0;
};
this.ws.onmessage = (event) => {
this.onMessage(JSON.parse(event.data));
};
this.ws.onclose = () => {
if (this.retries < this.maxRetries) {
const delay = Math.min(1000 * 2 ** this.retries, 30000);
this.retries++;
setTimeout(() => this.connect(), delay);
}
};
}
send(data: unknown) {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
}
}
close() {
this.maxRetries = 0; // 阻止后续重连
this.ws?.close();
}
}
async function fetchWithFallback( primary: () => Promise , fallback: () => Promise , cache?: T ): Promise { try { return await primary(); } catch (primaryError) { console.warn('Primary failed, trying fallback:', primaryError); try { return await fallback(); } catch (fallbackError) { console.warn('Fallback failed:', fallbackError); if (cache !== undefined) { console.warn('Using cached data'); return cache; } throw fallbackError; } } } // 使用示例 const data = await fetchWithFallback( () => fetchFromPrimaryAPI(), () => fetchFromBackupAPI(), cachedData );
// 指数退避延迟计算 const delay = Math.min(baseDelay * 2 ** attempt, maxDelay); // 加入抖动后的延迟 const jitteredDelay = delay * (0.5 + Math.random()); // 是否应重试的判断逻辑 const shouldRetry = error.status >= 500 || error.code === 'ETIMEDOUT' || error.code === 'ECONNRESET'; // 熔断器状态转换 Closed -> (failures >= threshold) -> Open Open -> (timeout elapsed) -> HalfOpen HalfOpen -> (success) -> Closed HalfOpen -> (failure) -> Open
相关专题
热门下载
相关下载
精品课程
共6课时 | 54.7万人学习
共89课时 | 134.1万人学习
共49课时 | 82.6万人学习
最新文章