Node.js 并发数 10000

标签 node.js

我是 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/

相关文章:

node.js - React 和 Node js 中的文件上传不起作用

node.js - Apache、 Node 、.htaccess

node.js - Docker 中 Apollo 服务器上传文件失败

node.js - Mongoose - 仅按日期部分排序日期,忽略时间

javascript - 修改后加载文件

javascript - 如何将多行输入通过管道传递给 Node.js 程序?

node.js - 无法在 Mongoose 中按 id 找到记录

javascript - vue-cli : dist/js/is not found in website source

javascript - 有没有办法监视对象的更改?

node.js - 在 Amazon Lambda 示例中使用异步?