nodejs高并发演示

压测脚本: ab -n 100 -c 100 http://127.0.0.1:8000/
http://127.0.0.1:8000/代码如下:
A).同步阻塞

//index.js
const http = require('http');
let result = 0;
http.createServer((req, res) => {
  let start = new Date();
  console.log(`request arrive--${start}`);
  var waitUntil = new Date(new Date().getTime() + 10 * 1000);
  while(waitUntil > new Date()){}
  console.log(`setTimeout--${result}-response end--${new Date()}`);
}).listen(8000);

执行node index.js
结果:
request arrive–Wed Apr 01 2020 11:05:40 GMT+0800 (GMT+08:00)
setTimeout–0-response end–Wed Apr 01 2020 11:05:50 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:05:50 GMT+0800 (GMT+08:00)
setTimeout–0-response end–Wed Apr 01 2020 11:06:00 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:06:00 GMT+0800 (GMT+08:00)
setTimeout–0-response end–Wed Apr 01 2020 11:06:10 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:06:10 GMT+0800 (GMT+08:00)
…..

能看到请求被阻塞了,需要等待

B).改成异步非阻塞

//index.js
const http = require('http');
const request = require('request');
let result = 0;
http.createServer((req, res) => {
  let start = new Date();
  console.log(`request arrive--${start}`);
  request('http://v.qq.com/', { json: true }, (err, ret, body) => {
    if (err) { return console.log(err); }
    console.log(`setTimeout--${result}-response end--${new Date()}`);
    res.end(`${result} end--${new Date()}`);
  });
}).listen(8000);

执行node index.js
结果如下:
request arrive–Wed Apr 01 2020 11:08:48 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:08:48 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:08:48 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:08:48 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:08:48 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:08:48 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:08:48 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:08:48 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:08:48 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:08:48 GMT+0800 (GMT+08:00)
request arrive–Wed Apr 01 2020 11:08:48 GMT+0800 (GMT+08:00)
……
Error: getaddrinfo ENOTFOUND v.qq.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26) {
errno: ‘ENOTFOUND’,
code: ‘ENOTFOUND’,
syscall: ‘getaddrinfo’,
hostname: ‘v.qq.com’
}
setTimeout–0-response end–Wed Apr 01 2020 11:09:16 GMT+0800 (GMT+08:00)
setTimeout–0-response end–Wed Apr 01 2020 11:09:17 GMT+0800 (GMT+08:00)
setTimeout–0-response end–Wed Apr 01 2020 11:09:18 GMT+0800 (GMT+08:00)
setTimeout–0-response end–Wed Apr 01 2020 11:09:18 GMT+0800 (GMT+08:00)
setTimeout–0-response end–Wed Apr 01 2020 11:09:18 GMT+0800 (GMT+08:00)
setTimeout–0-response end–Wed Apr 01 2020 11:09:18 GMT+0800 (GMT+08:00)
setTimeout–0-response end–Wed Apr 01 2020 11:09:19 GMT+0800 (GMT+08:00)
….
可以看到高并发的效果,每个请求都被处理了

此条目发表在NodeJs分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注