随着我对NodeJs的了解越来越多(我来自C#世界),我做了一个非常简单的测试,所以我可以了解expressJs请求处理流程:
const express = require('express');
const uuid = require('uuid');
const app = express();
const doSomething = (res, start, id) => {
const time = Date.now() - start;
console.log(`request ${id} processed and took ${time}ms`);
res.status(200).send({ id, took: `${time}ms` });
};
app.get('/', (req, res) => {
const id = uuid.v4();
const start = Date.now();
console.log(`request [1] accepted for ${id}`);
setTimeout(() => doSomething(res, start, id), 10000);
});
app.get('/2', (req, res) => {
const id = uuid.v4();
const start = Date.now();
console.log(`request [2] accepted for ${id}`);
setTimeout(() => doSomething(res, start, id), 5000);
});
app.listen(3000);
然后我打开浏览器3次,然后转到localhost:3000
,然后在第4个标签页中打开localhost:3000/2
...
我得到的输出是这样的:
> node .\index.js
request [1] accepted for 1c928996-484d-4658-b56a-620b9c1e4060
request [2] accepted for 13d564e1-4137-4c56-9bae-b106682cbed3
request 13d564e1-4137-4c56-9bae-b106682cbed3 processed and took 5001ms
request 1c928996-484d-4658-b56a-620b9c1e4060 processed and took 10002ms
request [1] accepted for 1b64f39c-8406-4edf-a887-533cd9e8abf0
request 1b64f39c-8406-4edf-a887-533cd9e8abf0 processed and took 10002ms
request [1] accepted for 5c77656f-2105-4d65-b40e-ae0cc86e96a4
request 5c77656f-2105-4d65-b40e-ae0cc86e96a4 processed and took 10001ms
我意识到第二个和第三个浏览器选项卡他们只是等待并等到第一个和第二个请求结束(因为它是相同的端点),但第四个选项卡被处理为一个新的请求... < / p>
是否可以在异步事项中处理每个请求,因此第二个请求和第三个请求只需等待10秒,而不是在处理上一个请求后10秒?
我只是想知道在生产中,如果内部调用API,为他们的一方需要更长的时间来处理(或者可能达到30秒的超时),我不希望所有下一次调用等待那个结束......
有没有办法做到这一点?
答案 0 :(得分:2)
尝试点击localhost:3000
和127.0.0.1:3000
,看看它们是否在同一时间结束。这可能是您的浏览器限制与同一资源的开放连接。
答案 1 :(得分:2)
看起来浏览器正在排队。 我尝试了一个边缘和铬,两个并行运行。
答案 2 :(得分:0)
我尝试从4个窗口卷曲并获得预期的响应
request [1] accepted for 1d37c1e9-da45-4b22-be57-de0c99d7a9b9
request [1] accepted for 2f7ee5e7-068e-4660-b606-75c3be9aa4bc
request [1] accepted for aa488dbc-da50-4578-a64c-22d47c28c301
request [2] accepted for a5181120-4709-4680-81ad-bae08c23c4f2
request a5181120-4709-4680-81ad-bae08c23c4f2 processed and took 5005ms
request 1d37c1e9-da45-4b22-be57-de0c99d7a9b9 processed and took 10004ms
request 2f7ee5e7-068e-4660-b606-75c3be9aa4bc processed and took 10002ms
request aa488dbc-da50-4578-a64c-22d47c28c301 processed and took 10003ms
窗口1,2和3
curl localhost:3000
窗口4
curl localhost:3000/2
所以看起来浏览器导致排队。