gpt4 book ai didi

node.js - Node HTTP 服务器的最大性能?

转载 作者:可可西里 更新时间:2023-11-01 16:56:04 26 4
gpt4 key购买 nike

我正在运行一个测试,试图从 Node HTTP 服务器获得最大传输速度。这是一个简单的服务器。在我的测试中,我有 50K 个虚拟客户端与服务器建立永久连接(我之前运行 ulimit -n 99999)。然后,在另一个事件发生时,到不同端口的 HTTP 连接,服务器向每个虚拟客户端发送一条消息。最后,所有客户端都会收到相应的消息。在我的测试中发送所有消息需要几分钟。是否有任何建议可以帮助我改进这些测量,以便我可以在几秒钟而不是几分钟内发送 50K 条消息?服务器在 m1.medium AWS 实例中运行。这个想法是为了提高同一平台的性能。

复制服务器代码:

var http = require("http");
var connectionResponse = [];
var connectionIndex = 0;

http.createServer(function(request, response) {
console.log("Received connection " + connectionIndex);
response.setTimeout(1200000, function() {
console.log("Socket timeout");
});
connectionResponse[connectionIndex] = response;
connectionIndex++;

}).listen(8888);

http.createServer(function(request, response) {
console.log("8887 connected - Will respond");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Triggered all responses");
response.end();

console.log("Begin notifications:" + new Date().toISOString());

for(var i = 0; i < connectionIndex; i++) {
connectionResponse[i].writeHead(200, {"Content-Type": "text/plain", "Content-Length": 4, "transfer-encoding" : ""});
connectionResponse[i].write("CAFE");
connectionResponse[i].end();
}
console.log("End notifications" + new Date().toISOString());

}).listen(8887);

最佳答案

设置这个 http://nodejs.org/api/http.html#http_agent_maxsockets数量足够

var http = require('http');
http.globalAgent.maxSockets = xxx;
var https = require('https');
https.globalAgent.maxSockets = xxx;

使用nodejs集群模块,http://nodejs.org/api/cluster.html

现在,关于集群,这实际上取决于您想要做什么。在您必须调整它之前,默认示例可以走很长一段路。一个例子是

var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}

cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else {
// Workers can share any TCP connection
// In this case its a HTTP server
http.createServer(function(req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
}

关于node.js - Node HTTP 服务器的最大性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28029227/

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