有什么办法可以使Express Server并行处理多个GET请求?
考虑以下示例:
server.js
var express = require('express')
var app = express();
app.get('/test01', function (req, res, next) {
for (i = 0; i < 1000000000; i++) {
var temp = i*i;
}
res.end('{"success" : "test01", "status" : 200}');
});
app.get('/test02', function (req, res, next) {
for (i = 0; i < 1; i++) {
var temp = i*i;
}
res.end('{"success" : "test02", "status" : 200}');
});
app.listen(8081, function () {
console.log("server listening at %s:%s", this.address().address, this.address().port)
})
client.js
var request = require("request");
request("http://127.0.0.1:8081/test01", function(error, response, body) {
console.log(body);
});
request("http://127.0.0.1:8081/test02", function(error, response, body) {
console.log(body);
});
运行client.js之后,输出为:
{"success" : "test01", "status" : 200}
{"success" : "test02", "status" : 200}
这意味着第二个请求将不得不等待第一个请求完成。
为了使两个请求并行运行并使“test01”成为非阻塞服务并在test01之前完成test02,我需要在server.js中进行哪些更改?
我不想更改client.js中的任何内容,也无法控制服务调用的时间。例如,test01可以被顺序调用3次,然后可以调用test02。
最佳答案
Node js是在您的计算机上运行的单个进程,即Node的单个实例在单个线程中运行。因此,如果您要进行大量的计算,那么 Node 可能不是正确的选择,也就是说, Node 的真正功能在于异步和回调。您可以尝试使用“群集” Node 模块,其思想不是在一个cpu单元上运行一个线程,而是根据#个cpu的数量运行尽可能多的线程,因此例如:在四核上,您最多可以运行4个 Node 实例。希望这可以帮助。