通过维护一个按优先级排序的待处理请求队列,并在空闲时触发执行来实现数据预队列策略。核心做法是定义一个包含请求配置和优先级的数组,利用 promise 链或并发限制器控制同时运行的请求数量,确保高优先级任务先被调度。

如何构建支持优先级的请求队列
使用一个有序数组来存储待执行的请求对象,每个对象包含 URL、HTTP 方法和优先级权重。当新请求加入时,根据权重插入到数组的正确位置,保证队列头部始终是高优先级任务。

class PriorityQueue {
constructor(maxConcurrent = 3) {
this.queue = [];
this.maxConcurrent = maxConcurrent;
this.activeCount = 0;
}
addRequest(url, options, priority) {
const request = { url, options, priority };
// 简单插入排序,保持优先级降序
let inserted = false;
for (let i = 0; i this.queue[i].priority) {
this.queue.splice(i, 0, request);
inserted = true;
break;
}
}
if (!inserted) {
this.queue.push(request);
}
this.processQueue();
}
async processQueue() {
while (this.activeCount 0) {
const req = this.queue.shift();
this.activeCount++;
try {
await fetch(req.url, req.options);
} catch (e) {
console.error('Fetch failed:', e);
} finally {
this.activeCount--;
this.processQueue(); // 递归处理下一个
}
}
}
}
const pq = new PriorityQueue(2);
pq.addRequest('/api/data', { method: 'GET' }, 10);
pq.addRequest('/api/image', { method: 'GET' }, 5);
上述代码展示了基本的优先级队列结构。`addRequest` 方法负责将新任务按优先级插入队列,并立即尝试启动处理流程。`processQueue` 方法检查当前活跃请求数是否低于最大并发限制,如果是则取出队首任务执行。执行完成后,无论成功或失败,都会递减活跃计数并再次调用自身以处理剩余任务。这种递归调用确保了队列中的任务能持续被消费,直到队列为空或达到并发上限。
如何处理请求完成后的状态更新与重试
在请求执行完毕后,需要更新内部状态以反映最新的数据或错误情况。对于失败的请求,可以设计简单的重试机制,将其重新放回队列尾部或特定优先级位置,避免永久丢失。

class RetryableQueue extends PriorityQueue {
constructor(maxConcurrent = 3, maxRetries = 3) {
super(maxConcurrent);
this.maxRetries = maxRetries;
this.retryMap = new Map(); // 记录重试次数
}
addRequest(url, options, priority) {
const retries = this.retryMap.get(url) || 0;
if (retries >= this.maxRetries) {
console.warn(`Max retries reached for ${url}`);
return;
}
super.addRequest(url, options, priority);
}
async processQueue() {
while (this.activeCount 0) {
const req = this.queue.shift();
this.activeCount++;
try {
await fetch(req.url, req.options);
this.retryMap.delete(req.url); // 成功后清除重试记录
} catch (e) {
console.error(`Retry needed for ${req.url}`);
const retries = this.retryMap.get(req.url) || 0;
this.retryMap.set(req.url, retries + 1);
// 将失败请求重新加入队列尾部,优先级降低
this.queue.push({ ...req, priority: req.priority - 1 });
} finally {
this.activeCount--;
this.processQueue();
}
}
}
}
const rQueue = new RetryableQueue(2, 2);
rQueue.addRequest('/api/unstable', {}, 10);
扩展后的 `RetryableQueue` 类继承自基础队列,增加了重试逻辑。`retryMap` 用于跟踪每个 URL 的重试次数。当 `fetch` 抛出异常时,程序会捕获错误,增加重试计数,并将请求重新推入队列末尾,同时略微降低其优先级以防止饥饿。如果重试次数超过阈值,则丢弃该请求。这种机制提高了在网络不稳定环境下的数据获取成功率。
基于输入参数动态调整并发限制的具体问题
当系统负载较高时,可以通过外部接口动态调整 `maxConcurrent` 参数,从而实时改变队列的处理能力。例如,在检测到内存占用过高时,自动减少并发数以避免 OOM。
// 假设有一个监控模块
function adjustConcurrency(newLimit) {
if (newLimit > 0 && newLimit newLimit) {
console.warn('Active requests exceed new limit');
}
}
}
adjustConcurrency(1);
这段代码演示了如何动态修改并发限制。虽然 `PriorityQueue` 实例本身不直接响应此变化,但 `processQueue` 循环在下一次迭代时会读取最新的 `maxConcurrent` 值。这意味着如果当前活跃请求数已经高于新设定的限制,新的请求将不会启动,直到活跃数下降到限制以下。这提供了一种简单的背压机制,防止系统在压力下崩溃。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











