前端開發(fā)中大并發(fā)量如何控制并發(fā)數(shù)
寫在前面
最近在進(jìn)行移動端h5開發(fā),首頁需要加載的資源很多,一個lottie動效需要請求70多張圖片,但是遇到安卓webview限制請求并發(fā)數(shù),導(dǎo)致部分圖片請求失敗破圖。當(dāng)然圖片資源可以做閑時加載和預(yù)加載,可以減輕播放動效時資源未加載的問題。
同樣的,業(yè)務(wù)開發(fā)也會遇到需要異步請求幾十個接口,如果同時并發(fā)請求瀏覽器會進(jìn)行限制請求數(shù),也會給后端造成請求壓力。
場景說明
現(xiàn)在有個場景:
請你實現(xiàn)一個并發(fā)請求函數(shù)concurrencyRequest(urls, maxNum),要求如下:
- 要求最大并發(fā)數(shù) maxNum。
- 每當(dāng)有一個請求返回,就留下一個空位,可以增加新的請求。
- 所有請求完成后,結(jié)果按照 urls 里面的順序依次打出(發(fā)送請求的函數(shù)可以直接使用fetch即可)。
初始實現(xiàn):
const preloadManger = (urls, maxCount = 5) => {
let count = 0; // 計數(shù) -- 用于控制并發(fā)數(shù)
const createTask = () => {
if (count < maxCount) {
const url = urls.pop(); // 從請求數(shù)組中取值
if (url) {
// 無論請求是否成功,都要執(zhí)行taskFinish
loader(url).finally(taskFinish);
// 添加下一個請求
count++;
createTask();
}
}
};
const taskFinish = () => {
count--;
createTask();
};
createTask();
};
// 進(jìn)行異步請求
const loader = async (url) => {
const res = await fetch(url).then(res=>res.json());
console.log("res",res);
return res
}
const urls = [];
for (let i = 1; i <= 20; i++) {
urls.push(`https://jsonplaceholder.typicode.com/todos/${i}`);
}
preloadManger(urls, 5)
請求狀態(tài):
可以看到上面的請求是每五個一組進(jìn)行請求,當(dāng)一個請求無論返回成功或是失敗,都會從請求數(shù)組中再取一個請求進(jìn)行補(bǔ)充。
設(shè)計思路
那么,我們可以考慮使用隊列去請求大量接口。
思路如下:
假定最大并發(fā)數(shù)是maxNum=5,圖中對接口進(jìn)行了定義編號,當(dāng)請求隊列池中有一個請求返回后,就向池子中新增一個接口進(jìn)行請求,依次直到最后一個請求執(zhí)行完畢。
當(dāng)然,要保證程序的健壯性,需要考慮一些邊界情況,如下:
- 當(dāng)初始請求數(shù)組urls的長度為0時,此時請求結(jié)果數(shù)組results是個空數(shù)組。
- 最大并發(fā)數(shù)maxNums>urls的長度時,請求數(shù)為urls的長度。
- 需要定義計數(shù)器count去判斷是否全部請求完畢。
- 無論請求成功與否,都應(yīng)該將結(jié)果存在結(jié)果數(shù)組results中。
- 結(jié)果數(shù)組results和urls數(shù)組的順序保持一致,方便存取。
代碼實現(xiàn)
在前面的初始實現(xiàn)的代碼中,雖然都能滿足基本需求,但是并沒有考慮一些邊界條件,對此需要根據(jù)上面設(shè)計思路重新實現(xiàn)得到:
// 并發(fā)請求函數(shù)
const concurrencyRequest = (urls, maxNum) => {
return new Promise((resolve) => {
if (urls.length === 0) {
resolve([]);
return;
}
const results = [];
let index = 0; // 下一個請求的下標(biāo)
let count = 0; // 當(dāng)前請求完成的數(shù)量
// 發(fā)送請求
async function request() {
if (index === urls.length) return;
const i = index; // 保存序號,使result和urls相對應(yīng)
const url = urls[index];
index++;
console.log(url);
try {
const resp = await fetch(url);
// resp 加入到results
results[i] = resp;
} catch (err) {
// err 加入到results
results[i] = err;
} finally {
count++;
// 判斷是否所有的請求都已完成
if (count === urls.length) {
console.log('完成了');
resolve(results);
}
request();
}
}
// maxNum和urls.length取最小進(jìn)行調(diào)用
const times = Math.min(maxNum, urls.length);
for(let i = 0; i < times; i++) {
request();
}
})
}
測試代碼:
const urls = [];
for (let i = 1; i <= 20; i++) {
urls.push(`https://jsonplaceholder.typicode.com/todos/${i}`);
}
concurrencyRequest(urls, 5).then(res => {
console.log(res);
})
請求結(jié)果:
上面代碼基本實現(xiàn)了前端并發(fā)請求的需求,也基本滿足需求,在生產(chǎn)中其實有很多已經(jīng)封裝好的庫可以直接使用。比如:p-limit【https://github.com/sindresorhus/p-limit】
閱讀p-limit源碼
import Queue from 'yocto-queue';
import {AsyncResource} from '#async_hooks';
export default function pLimit(concurrency) {
// 判斷這個參數(shù)是否是一個大于0的整數(shù),如果不是就拋出一個錯誤
if (
!((Number.isInteger(concurrency)
|| concurrency === Number.POSITIVE_INFINITY)
&& concurrency > 0)
) {
throw new TypeError('Expected `concurrency` to be a number from 1 and up');
}
// 創(chuàng)建隊列 -- 用于存取請求
const queue = new Queue();
// 計數(shù)
let activeCount = 0;
// 用來處理并發(fā)數(shù)的函數(shù)
const next = () => {
activeCount--;
if (queue.size > 0) {
// queue.dequeue()可以理解為[].shift(),取出隊列中的第一個任務(wù),由于確定里面是一個函數(shù),所以直接執(zhí)行就可以了;
queue.dequeue()();
}
};
// run函數(shù)就是用來執(zhí)行異步并發(fā)任務(wù)
const run = async (function_, resolve, arguments_) => {
// activeCount加1,表示當(dāng)前并發(fā)數(shù)加1
activeCount++;
// 執(zhí)行傳入的異步函數(shù),將結(jié)果賦值給result,注意:現(xiàn)在的result是一個處在pending狀態(tài)的Promise
const result = (async () => function_(...arguments_))();
// resolve函數(shù)就是enqueue函數(shù)中返回的Promise的resolve函數(shù)
resolve(result);
// 等待result的狀態(tài)發(fā)生改變,這里使用了try...catch,因為result可能會出現(xiàn)異常,所以需要捕獲異常;
try {
await result;
} catch {}
next();
};
// 將run函數(shù)添加到請求隊列中
const enqueue = (function_, resolve, arguments_) => {
queue.enqueue(
// 將run函數(shù)綁定到AsyncResource上,不需要立即執(zhí)行,對此添加了一個bind方法
AsyncResource.bind(run.bind(undefined, function_, resolve, arguments_)),
);
// 立即執(zhí)行一個異步函數(shù),等待下一個微任務(wù)(注意:因為activeCount是異步更新的,所以需要等待下一個微任務(wù)執(zhí)行才能獲取新的值)
(async () => {
// This function needs to wait until the next microtask before comparing
// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
// when the run function is dequeued and called. The comparison in the if-statement
// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
await Promise.resolve();
// 判斷activeCount是否小于concurrency,并且隊列中有任務(wù),如果滿足條件就會將隊列中的任務(wù)取出來執(zhí)行
if (activeCount < concurrency && queue.size > 0) {
// 注意:queue.dequeue()()執(zhí)行的是run函數(shù)
queue.dequeue()();
}
})();
};
// 接收一個函數(shù)fn和參數(shù)args,然后返回一個Promise,執(zhí)行出隊操作
const generator = (function_, ...arguments_) => new Promise(resolve => {
enqueue(function_, resolve, arguments_);
});
// 向外暴露當(dāng)前的并發(fā)數(shù)和隊列中的任務(wù)數(shù),并且手動清空隊列
Object.defineProperties(generator, {
// 當(dāng)前并發(fā)數(shù)
activeCount: {
get: () => activeCount,
},
// 隊列中的任務(wù)數(shù)
pendingCount: {
get: () => queue.size,
},
// 清空隊列
clearQueue: {
value() {
queue.clear();
},
},
});
return generator;
}
整個庫只有短短71行代碼,在代碼中導(dǎo)入了yocto-queue庫,它是一個微型的隊列數(shù)據(jù)結(jié)構(gòu)。
手寫源碼
在進(jìn)行手撕源碼時,可以借助數(shù)組進(jìn)行簡易的實現(xiàn):
class PLimit {
constructor(concurrency) {
this.concurrency = concurrency;
this.activeCount = 0;
this.queue = [];
return (fn, ...args) => {
return new Promise(resolve => {
this.enqueue(fn, resolve, args);
});
}
}
enqueue(fn, resolve, args) {
this.queue.push(this.run.bind(this, fn, resolve, args));
(async () => {
await Promise.resolve();
if (this.activeCount < this.concurrency && this.queue.length > 0) {
this.queue.shift()();
}
})();
}
async run(fn, resolve, args) {
this.activeCount++;
const result = (async () => fn(...args))();
resolve(result);
try {
await result;
} catch {
}
this.next();
}
next() {
this.activeCount--;
if (this.queue.length > 0) {
this.queue.shift()();
}
}
}
小結(jié)
在這篇文章中,簡要介紹了為什么要進(jìn)行并發(fā)請求,闡述了使用請求池隊列實現(xiàn)并發(fā)請求的設(shè)計思路,簡要實現(xiàn)代碼。
此外,還閱讀分析了p-limit的源碼,并使用數(shù)組進(jìn)行簡要的源碼編寫,以實現(xiàn)要求。
參考文章
- 【源碼共讀】大并發(fā)量如何控制并發(fā)數(shù)https://juejin.cn/post/7179220832575717435?searchId=20240430092814392DC2208C545E691A26
- 前端實現(xiàn)并發(fā)控制網(wǎng)絡(luò)請求https://mp.weixin.qq.com/s/9uq2SqkcMSSWjks0x7RQJg。