通过维护一个优先级队列和状态机,结合递归调用与指数退避策略,可以实现具备自动重试能力的异步任务队列。核心做法是定义一个包含任务列表的类,每个任务携带最大重试次数、当前重试计数及延迟时间,执行时捕获异常并判断是否继续入队或抛出错误。

retryQueue 如何管理任务生命周期
该队列通过内部数组存储待处理任务,利用 async/await 顺序执行来保证并发控制。每个任务对象必须包含 fn(异步函数)、maxRetries(最大重试数)和 delay(重试间隔)。当任务执行成功时,从队列移除;失败时检查重试次数,若未超限则重新加入队列尾部并等待指定时间,否则标记为失败。

class RetryQueue {
constructor() {
this.queue = [];
this.processing = false;
}
async addTask(task) {
this.queue.push({
...task,
retries: 0,
id: Math.random().toString(36).substr(2, 9)
});
if (!this.processing) await this.process();
}
async process() {
this.processing = true;
while (this.queue.length > 0) {
const task = this.queue.shift();
try {
await task.fn();
console.log(`Task ${task.id} succeeded`);
} catch (error) {
task.retries++;
if (task.retries <= task.maxRetries) {
console.log(`Task ${task.id} failed, retrying in ${task.delay}ms...`);
await new Promise(r => setTimeout(r, task.delay));
this.queue.push(task);
} else {
console.error(`Task ${task.id} permanently failed`);
}
}
}
this.processing = false;
}
}
// 使用示例
const queue = new RetryQueue();
queue.addTask({
fn: async () => { throw new Error('Network error'); },
maxRetries: 3,
delay: 1000
});上述代码展示了基本的生命周期管理。输入为一个模拟网络错误的函数,预期结果是任务在三次重试后最终报错。通过 process 方法中的循环,确保队列清空前持续处理任务。这种设计避免了并发竞争,适合对顺序有要求的场景。
立即学习“Java免费学习笔记(深入)”;
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
如何实现指数退避与并发限制
为了优化重试效率,通常采用指数退避算法计算延迟时间,即 delay * Math.pow(2, retries)。同时,通过引入信号量或计数器可以限制同时运行的任务数量,防止资源耗尽。修改 addTask 逻辑以支持并发控制,并在 process 中根据当前活跃任务数决定是否立即执行或挂起。

class ConcurrentRetryQueue extends RetryQueue {
constructor(maxConcurrency = 5) {
super();
this.maxConcurrency = maxConcurrency;
this.activeTasks = 0;
}
async addTask(task) {
const fullTask = {
...task,
retries: 0,
id: Math.random().toString(36).substr(2, 9),
calculateDelay: () => task.delay * Math.pow(2, task.retries)
};
while (this.activeTasks >= this.maxConcurrency) {
await new Promise(resolve => setTimeout(resolve, 100));
}
this.activeTasks++;
this.queue.push(fullTask);
if (!this.processing) this.process();
}
async process() {
this.processing = true;
while (this.queue.length > 0 || this.activeTasks > 0) {
if (this.queue.length > 0 && this.activeTasks < this.maxConcurrency) {
const task = this.queue.shift();
this.executeTask(task);
} else {
await new Promise(resolve => setTimeout(resolve, 100));
}
}
this.processing = false;
}
async executeTask(task) {
try {
await task.fn();
} catch (error) {
task.retries++;
if (task.retries <= task.maxRetries) {
await new Promise(r => setTimeout(r, task.calculateDelay()));
this.queue.push(task);
}
} finally {
this.activeTasks--;
}
}
}此版本引入了并发限制和指数退避。输入为多个高负载任务,预期结果是系统自动调节并发度并动态增加重试延迟。通过 activeTasks 跟踪当前运行数,确保不超过 maxConcurrency。这种实现更适合生产环境中的批量数据处理。
任务失败后的持久化存储策略
在实际应用中,内存队列重启后会丢失数据,因此需要将失败任务持久化到数据库或文件系统中。可以在 catch 块中调用 saveToDisk 或 db.insert 将任务元数据写入存储。恢复时,启动服务读取持久化数据并重新注入队列。关键是要确保原子性,避免重复消费或数据丢失。
async function saveToDisk(task) {
// 模拟写入文件系统或数据库
const data = JSON.stringify({
id: task.id,
fn: task.fn.toString(),
retries: task.retries,
maxRetries: task.maxRetries,
lastError: 'Simulated error'
});
console.log(`Persisted task ${task.id}:`, data);
}
// 在 catch 块中调用
try {
await task.fn();
} catch (error) {
task.retries++;
if (task.retries <= task.maxRetries) {
await saveToDisk(task); // 持久化失败任务
await new Promise(r => setTimeout(r, task.calculateDelay()));
this.queue.push(task);
}
}通过持久化机制,即使进程崩溃,任务也能在重启后继续执行。输入为任意失败任务,预期结果是任务信息被安全保存。这种策略提高了系统的鲁棒性,适用于关键业务场景。注意在实际实现中需处理序列化问题,如函数无法直接 JSON 序列化,可改用标识符映射。

















