[英]NodeJS Multiple Async Requests
我有以下代码。 它模拟时间密集型请求。 我希望 NodeJS 一次处理“无限”数量的请求。 相反,它一次不能处理两个以上的请求。 我该怎么做才能说服 NodeJS 一次处理多个请求?
const http = require('http');
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function response() {
await sleep(10000);
return '';
}
http.createServer(async function (req, res) {
console.log('Request start...');
const html = await response();
console.log('Request end...');
res.write(html);
res.end();
}).listen(3000);
$ node server.js
Request start...
Request start...
Request end...
Request start...
Request end...
Request end...
Request start...
Request start...
Request end...
...
我在 macOS Mojave 上运行 NodeJS。
$ node -v
v14.11.0
节点实际上是同时处理所有的请求。 结果归结为您的“测试”方法,我假设以下几点与您的方法条件有关:
如果您通过浏览器进行测试:
在这种情况下,一个糟糕的测试场景示例:在浏览器中打开多个选项卡,并快速连续地从每个选项卡发送请求。
观察真相:
您可以通过多种方法对多个并发请求进行准确测试,但这里有几个简单的选项:
1. 打开多个终端实例并从每个实例发送请求:
重击
curl http://localhost:3000
(或在一个 Bash 实例中:)
curl http://localhost:3000 & curl http://localhost:3000 & curl http://localhost:3000 & curl http://localhost:3000
电源外壳:
Invoke-WebRequest http://localhost:3000
2.通过一个Chrome标签请求,反复刷新。
我还修改了您的代码段以帮助指示请求/响应对:
const http = require('http');
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function response() {
await sleep(10000);
return '';
}
let i = 1;
http.createServer(async function (req, res) {
let j = i;
i++;
console.log('Request start...', j);
const html = await response();
console.log('Request end...', j);
res.write(html);
res.end();
}).listen(3000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.