const Koa = require('koa');
const app = new Koa();
app.use((ctx, next) => {
console.log('middleware 1');
setTimeout(() => {
next();
}, 3000);
ctx.body = 'hello';
});
app.use((ctx, next) => {
console.log('middleware 2');
});
app.listen(8989);
const Koa = require('koa');
const app = new Koa();
const queue = [];
app.use(async (ctx, next) => {
setTimeout(() => {
queue.shift()();
}, 3000);
await delay();
ctx.body = 'hello';
});
function delay() {
return new Promise((resolve, reject) => {
queue.push(resolve);
});
}
app.listen(8989);
async function requestSomeApi() {
// 如果已经超过了最大并发
if (counter > maxAllowedRequest) {
await delay();
}
counter++;
const result = await request('http://some.api');
counter--;
queue.shift()();
return result;
}
async function limitWrapper(func, maxAllowedRequest) {
const queue = [];
const counter = 0;
return async function () {
if (counter > maxAllowedRequest) {
await new Promise((resolve, reject) => {
queue.push(resolve);
});
}
counter++;
const result = await func();
counter--;
queue.shift()();
return result;
}
}
async function limiter(ctx, next) => {
// 如果超过了最大并发数目
if (counter >= maxAllowedRequest) {
// 如果当前队列中已经过长
await new Promise((resolve, reject) => {
queue.push(resolve);
});
}
store.counter++;
await next();
store.counter--;
queue.shift()();
};
router.use('/api', rateLimiter);
ctx.res.on('close', () => {
const index = queue.findIndex(item => item.hash === hash);
if (index > -1) {
queue.splice(index, 1);
}
});
const server = app.listen(config.port); server.timeout = DEFAULT_TIMEOUT;
if (queue.length > maxAllowedRequest) {
ctx.body = 'error message';
return;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有