gpt4 book ai didi

node.js - Nodejs Express http 服务器如何处理并发请求?

转载 作者:太空宇宙 更新时间:2023-11-03 23:56:19 25 4
gpt4 key购买 nike

我正在构建一个 Node.js 应用程序,并想了解如何处理并发请求。

我构建了一个测试服务器,通过等待 10 秒来模拟高 CPU 负载。为了测试行为,我打开两个浏览器选项卡并同时刷新页面。

const http      = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const server = require('http').createServer(app);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.get('*', function (req, res, next) {
var requestTime = new Date().getTime(),
executionTime;

doHeavyWork(requestTime, function(error){
res.send({
requestTime : requestTime,
executionTime : executionTime
});
});

});

function doHeavyWork (requestTime, callback) {
var sleepSeconds = 10;

while (requestTime + sleepSeconds*1000 >= new Date().getTime()) {}

callback(null);
}

server.listen(1337, '127.0.0.1');

根据我对 Node.js 的了解,我希望两个选项卡能够同时完成加载。实际上,最先刷新的选项卡也会先完成。下一个选项卡将在 10 秒后加载。所以基本上,服务器一次处理一个请求,而不是同时处理它们。我在这里缺少什么?

最佳答案

无需进入 nitty gritty 即可回答您的问题关于 Node 的工作原理(我建议您阅读),您看到的行为正是我根据您的代码所期望看到的。

对于运行的每个 Node 实例,都有一个处理线程,在大容量场景中,建议尽可能少地执行 CPU 密集型操作,以免阻塞该线程。在您的示例中,每个请求都运行一个 10 秒的 CPU 密集型操作,这意味着在该请求完成之前 Node 无法处理任何新请求。

如果您想更好地演示 Node 的吞吐量,请使用非阻塞示例,例如使用定时器

app.get('*', function (req, res, next) {
var requestTime = new Date().getTime(),
executionTime;

setTimeout(() => {
res.send({
requestTime,
executionTime: new Date().getTime()
});
}, 10000);
});

关于node.js - Nodejs Express http 服务器如何处理并发请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56941047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com