Node.js 通过进程、线程优化的性能

1. node.js 单线程的特点

node.js 以异步非阻塞单线程,作为其执行速度的保障。什么是非阻塞单线程?

举一个现实生活中的例子,我去巢大食堂打饭,我选择了A套餐,然后工作人员区为我配餐,我就在旁边等着直到阿姨叫号然后我取餐。这个过程是同步

如果工作人员在为我配餐的同时,仍然可以接受排在我后面的同学的点餐,这样餐厅并没有因为我在等待A套餐而停止。这个过程是非阻塞

如果我在阿姨为我配餐的同时,我去旁边小超市买了杯冷饮,等阿姨叫号时我再去取餐。这个过程就是异步非阻塞,同时阿姨叫号我去取餐的行为叫做回调

  • 高性能(不用考虑多线程间来回调用引起性能的损耗)
  • 线程安全(不用担心同意变量会被多线程进行读写而造成程序的崩溃)
  • 底层多线程
    说node.js 是单线程其实也是不全面的,node.js 底层库会使用libuv调用多线程来处理I/O 操作。这就像食堂只有一个窗口,只能有按顺序一个个的接收点餐,但是后厨配菜的员工却有很多,他们各司其职保证出餐的速度。

如果服务器是多核且有充足的物理资源,如何充分发挥这些物理资源达到性能最大化。既食堂后厨有很多大师傅,一个窗口售卖的速度太慢,许多大师傅都是空闲的窗台。邪恶的资本家你们懂的?

2.如何通过多线程提高node.js 的性能

  • cluster: 为了利用多核系统,用户有时会想启动一个 Node.js 进程的集群去处理负载。
const Koa = require('Koa');
const koaRouter = require('koa-router');

const app = new Koa();
const router = new koaRouter();

function fibo(n) {
    return n > 1 ? fibo(n - 1) + fibo(n-2) : 1
}
app.use(router['routes']());

router.get('/', function(ctx, next) {
    var result = fibo(35);
    ctx.body = `${result}`;
});

if (!module.parent) {
    app.listen(8080);
    console.log(`Server was start.`);
}

通过ab 压力测试命令:

ab -c 20 -n 100 http://localhost:8080/

没有经过cluster 集群优化:

Server Software:        
Server Hostname:        localhost
Server Port:            8080

Document Path:          /
Document Length:        8 bytes

Concurrency Level:      20
Time taken for tests:   13.569 seconds
Complete requests:      100
Failed requests:        0
Total transferred:      14300 bytes
HTML transferred:       800 bytes
Requests per second:    7.37 [#/sec] (mean)
Time per request:       2713.723 [ms] (mean)
Time per request:       135.686 [ms] (mean, across all concurrent requests)
Transfer rate:          1.03 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.2      0       1
Processing:   155 2465 622.9   2738    2762
Waiting:      153 2465 623.0   2737    2762
Total:        155 2465 622.8   2738    2762

Percentage of the requests served within a certain time (ms)
  50%   2738
  66%   2743
  75%   2746
  80%   2747
  90%   2753
  95%   2757
  98%   2761
  99%   2762
 100%   2762 (longest request)

通过cluster 集群优化后:

const Koa = require('Koa');
const koaRouter = require('koa-router');
const numCpus = require('os').cpus().length;
const cluster = require('cluster');

const app = new Koa();
const router = new koaRouter();

if (cluster.isMaster) {
    console.log(`${numCpus}`);
    for (var index = 0; index < numCpus; index++) {
        cluster.fork();
    }
} else {
    app.use(router['routes']());
    router.get('/', function(ctx, next) {
        var result = fibo(35);
        ctx.body = `${result}`;
    });
    if (!module.parent) {
        app.listen(8080);
        console.log(`Server was start.`);
    }
}

function fibo(n) {
    return n > 1 ? fibo(n - 1) + fibo(n-2) : 1
}

通过ab 压力测试命令:

ab -c 20 -n 100 http://localhost:8080/

Server Software:        
Server Hostname:        localhost
Server Port:            8080

Document Path:          /
Document Length:        8 bytes

Concurrency Level:      20
Time taken for tests:   6.513 seconds
Complete requests:      100
Failed requests:        0
Total transferred:      14300 bytes
HTML transferred:       800 bytes
Requests per second:    15.35 [#/sec] (mean)
Time per request:       1302.524 [ms] (mean)
Time per request:       65.126 [ms] (mean, across all concurrent requests)
Transfer rate:          2.14 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.5      0       2
Processing:   279 1198 258.7   1294    1335
Waiting:      279 1198 258.7   1294    1335
Total:        281 1198 258.3   1295    1335

Percentage of the requests served within a certain time (ms)
  50%   1295
  66%   1301
  75%   1303
  80%   1308
  90%   1322
  95%   1328
  98%   1333
  99%   1335
 100%   1335 (longest request)

对比两次的测试结果:
优化后,
Requests per second (每秒处理的任务数) 由 7.37 提高到 15.35.
Time per request (每个用户的平均处理时间) 由 135.686 降低到 65.126

3. 如何通过多进程提高node.js 的性能

main.js

const Koa = require('Koa');
const koaRouter = require('koa-router');
const fork = require('child_process').fork;

const app = new Koa();
const router = new koaRouter();

app.use(router['routes']());
router.get('/', function(ctx, next) {
    var worker = fork('./work_fibo.js');
    worker.on('message', function(m) {
        if ('object' === typeof m && m.type === 'fibo') {
            worker.kill();
            ctx.body = m.result.toString();
        }
    });

    worker.send({type: "fibo", num: 35}, (err) => {
        console.log(`${err}`);
    });
    console.log(`${worker.pid}`); 
    
});

if (!module.parent) {
    app.listen(8080);
    console.log(`Server was start.`);
}

work_fibo.js

var fibo = function fibo(n) {
    return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1;
}

process.on('message', function(m) {   
    if (typeof m === 'object' && m.type === 'fibo') {
        var num = fibo(m.num);
        process.send({type: 'fibo', result: num});
    }
});

process.on('SIGHUP', function() {
    process.exist();
});

通过ab 压力测试命令:

ab -c 20 -n 100 http://localhost:8080/

Server Software:        
Server Hostname:        localhost
Server Port:            8080

Document Path:          /
Document Length:        9 bytes

Concurrency Level:      20
Time taken for tests:   3.619 seconds
Complete requests:      100
Failed requests:        0
Non-2xx responses:      100
Total transferred:      15100 bytes
HTML transferred:       900 bytes
Requests per second:    27.63 [#/sec] (mean)
Time per request:       723.764 [ms] (mean)
Time per request:       36.188 [ms] (mean, across all concurrent requests)
Transfer rate:          4.07 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   4.5      0      43
Processing:    21  611 270.7    650    1134
Waiting:       18  610 270.7    649    1132
Total:         22  612 270.2    652    1134

Percentage of the requests served within a certain time (ms)
  50%    652
  66%    744
  75%    794
  80%    835
  90%    958
  95%   1054
  98%   1122
  99%   1134
 100%   1134 (longest request)

对比两次的测试结果:
优化后,
Requests per second (每秒处理的任务数) 由 7.37 提高到 15.35 最后通过进程优化后达到 27.63
Time per request (每个用户的平均处理时间) 由 135.686 降低到 65.126 最后通过进程优化后达到 36.188

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容