问题描述
我有一个使用HapiJS框架开发的API。如果处理程序返回承诺,则后续请求将等待完成现有请求。所以基本上我在访问API时正在执行异步过程。
请找到以下示例:
// Server Creation ...
// Route Creation
server.route({
method: 'GET',path: '/v1/check',handler: () => {
console.log('Check');
return new Promise((resolve) => {
setTimeout(() => {
console.log('Check Response')
resolve({check: 1});
},1000);
});
}
});
在浏览器的3个不同选项卡中执行相同的路由并同时全部重新加载时。
日志:
Check
Check Response
Check
Check Response
Check
Check Response
预期日志:
Check
Check
Check
Check Response
Check Response
Check Response
// Not expecting the same log,but wanted parallel execution.
所以我的疑问是,如果100个用户使用相同的API,那么第100个请求必须等待99个请求完成?
与输出有些混淆。
解决方法
使用浏览器进行测试可能并不理想,因为它们通常会限制允许的并发连接数量。
当我使用Apache Bench运行示例时,得到了预期的结果。
服务器:
'use strict';
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,host: 'localhost'
});
server.route({
method: 'GET',path: '/v1/check',handler: () => {
console.log('Check');
return new Promise((resolve) => {
setTimeout(() => {
console.log('Check Response')
resolve({check: 1});
},1000);
});
}
});
await server.start();
console.log('Server running on %s',server.info.uri);
};
init();
测试:
docker run -it --net="host" --rm -t devth/alpine-bench -n10 -c10 http://host.docker.internal:3000/v1/check
结果:
$ node index.js
Server running on http://localhost:3000
Check
Check
Check
Check
Check
Check
Check
Check
Check
Check
Check Response
Check Response
Check Response
Check Response
Check Response
Check Response
Check Response
Check Response
Check Response
Check Response