3

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

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

4

2 回答 2

4

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

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

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打开的文件太多)您必须增加最大值。允许打开的文件数 -> ulimit

于 2012-04-12T08:40:51.230 回答
0

如果您不想使用 for 循环,我想您可以重复 http 请求调用 10 000 次。它可能会起作用。这是否是一个好主意,嗯,不太确定。

于 2012-04-12T06:17:08.213 回答