gpt4 book ai didi

Node.js 并发数 10000

转载 作者:搜寻专家 更新时间:2023-10-31 23:43:54 26 4
gpt4 key购买 nike

我是 Node 的新手。我想问一下,是否可以从node.js发送http请求到任何一台每秒并发10000的服务器?无需将代码放入 for 循环并运行 10000 次。

apache 基准测试在 node.js 中可能做的事情

最佳答案

前段时间我写了一个具有 ApacheBench 基本功能的 node.js 脚本:

(标有//# 的行应该根据您的需要进行更改)

var http=require('http');

var inp_num_requests=20000; // #
var inp_concurrency =10000; // #

var options={
host:'127.0.0.1', // #
port:80, // #
path:'/', // #
method:'GET',
agent:false
};

var active=0;
var num_reqests=0;
var errors=0;
var total_bytes=0;
var last=-1;
var timer=setInterval(function(){
if (last!=num_reqests) console.log(num_reqests+'/'+inp_num_requests,'err:',errors);
last=num_reqests;
},1000);
var start_time=+new Date;

function checkEnd(){
if (num_reqests<inp_num_requests) {
makeRequest();
}else if(!active){
clearInterval(timer);
console.log('\nFinished '+num_reqests+' requests');

var took=((+new Date)-start_time)/1000;
console.log(
'Time taken for tests: '+took+' seconds\n'+
'Complete requests: '+num_reqests+'\n'+
'Failed requests: '+errors+'\n'+
'HTML transferred: '+total_bytes+' bytes\n'+
'Requests per second: '+(num_reqests/took)+' [#/sec]\n'+
'Time per request: '+(took/num_reqests*1000)+' [ms] (mean, across all concurrent requests)\n'


);
}
}

function makeRequest(){
active++;
num_reqests++;
var r=http.request(options,function(res){
res.on('data',function(chunk){
total_bytes+=chunk.length;
});
res.once('end',function(){
active--;
checkEnd();
});
});
r.once('error',function(e){
if ('ECONNRESET'!=e.code) {
console.log(e);
process.exit();
}
errors++;
active--;
checkEnd();
});
if (active<inp_concurrency) makeRequest();
r.end();

}

makeRequest();

示例输出:

10000/20000 err: 0
11622/20000 err: 0
12036/20000 err: 0
20000/20000 err: 0

Finished 20000 requests
Time taken for tests: 10.817 seconds
Complete requests: 20000
Failed requests: 0
HTML transferred: 2037900 bytes
Requests per second: 1848.9414810021262 [#/sec]
Time per request: 0.54085 [ms] (mean, across all concurrent requests)


如果出现以下错误: Error: connect EMFILE (too many open files) 你必须增加最大值。允许的打开文件数 -> ulimit

关于Node.js 并发数 10000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10117524/

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