benchmark pm2的cluster模式發佈web app的性能與相關問題解決方法

pm2以cluster集羣方式發佈app,能夠高效地利用多核cpu,有效提高吞吐量。在上週對公司的redmine服務器進行性能調優後,深感ruby on rails的性能低下,此次測試nodejs的sails框架,被其性能深深折服。node

 

如下是使用pm2發佈nodejs 應用的經歷:git

一:記錄出現的問題記錄。github

1. pm2 start app.js -i 0 web

   當使用以上指令時,出現提示說pm2 的cluster模式很是不穩定,建議不使用。可是官網上面倒是推薦使用,爲何呢?sql

原來個人node版本太低,只有0.10.36,建議安裝0.11.x以上的版本,而後再運行此命令,才能啓動cluster模式。apache

2. 當我升級node到了0.12.13版以後,運行卻發現依然是mode:fork模式。以下圖:ruby

──────────┬────┬──────┬───────┬────────┬─────────┬────────┬─────────────┬──────────┐
│ App name   │ id │ mode │ pid │ status │ restart │ uptime │ memory │ watching │
├──────────┼────┼──────┼───────┼────────┼─────────┼────────┼─────────────┼──────────┤
│ app            │ 0 │ fork    │ 15375 │ online │ 0 │ 0s │ 19.297 MB │ disabled │
└──────────┴────┴──────┴───────┴────────┴─────────┴────────┴─────────────┴──────────┘服務器

緣由是:pm2在問題一中啓動以後並無關閉,而是一直以deamon的形式運行着,並且會保持其啓動模式,也就是說以前若是啓動deamon是fork模式,那麼以後你用pm2 start app.js -i 2時,即便指定了-i 也再也不生效。app

解決辦法有兩種:框架

1. 使用-f 參數強制其更換啓動模式:pm2 start app.js -i 2 -f

2. 使用pm2 kill ,關閉deamon,而後從新使用pm2 start app.js開啓。

 

2、nodejs性能

爲了可以測試node在接近實際應用場景下地性能,我採用了一個sails框架,方便我快速搭建一個有sql數據訪問的web app的性能。

而後在我買的一個ECS雲服務器上測試,我雲服務器的性能很是差,只有單核CPU+512內存,可是測試下來卻發現,nodejs的異步特性使得其性能表現極爲讓人震驚。如下是用pm2以單進程形式發佈的app, 請求一個包含sql查找操做的URL, ab測試結果以下:

ab -n 1000 -c 160 http://localhost:1337/User/find/1
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests


Server Software:
Server Hostname: localhost
Server Port: 1337

Document Path: /User/find/1
Document Length: 40 bytes

Concurrency Level: 160
Time taken for tests: 3.724 seconds
Complete requests: 1000
Failed requests: 0
Write errors: 0
Non-2xx responses: 1000
Total transferred: 464566 bytes
HTML transferred: 40000 bytes
Requests per second: 268.52 [#/sec] (mean)
Time per request: 595.862 [ms] (mean)
Time per request: 3.724 [ms] (mean, across all concurrent requests)
Transfer rate: 121.82 [Kbytes/sec] received

Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 1 2.9 0 14
Processing: 213 579 112.2 588 959
Waiting: 213 578 112.2 587 958
Total: 213 580 112.2 588 961

Percentage of the requests served within a certain time (ms)
50% 588
66% 600
75% 611
80% 618
90% 633
95% 787
98% 898
99% 943
100% 961 (longest request)
View Code

能夠看出,單進程狀況下,抗住了將近270次請求,並且該請求仍是包含sql操做的哦。

而後,換成用pm2 cluster模式,3個nodes, 性能反倒變成了120次,我想應該有兩個緣由,1是內存受限,2是單核CPU下,採用cluster只會增長cpu切換帶來的負面影響,下降了cpu的有效利用率。

 

好了,若是各位對與node的性能感興趣能夠到個人github上clone sailsBench項目下來【參考1】,嘗試下用pm2發佈,而後用ab測試其性能。

 

參考:

1. https://github.com/todototry/sailsBench/

相關文章
相關標籤/搜索