pm2以cluster集群方式發布app,可以高效地利用多核cpu,有效提升吞吐量。在上周對公司的redmine服務器進行性能調優后,深感ruby on rails的性能低下,這次測試nodejs的sails框架,被其性能深深折服。
以下是使用pm2發布nodejs 應用的經歷:
一:記錄出現的問題記錄。
1. pm2 start app.js -i 0
當使用以上指令時,出現提示說pm2 的cluster模式非常不穩定,建議不使用。但是官網上面卻是推薦使用,為什么呢?
原來我的node版本過低,只有0.10.36,建議安裝0.11.x以上的版本,然后再運行此命令,才能啟動cluster模式。
2. 當我升級node到了0.12.13版之后,運行卻發現依然是mode:fork模式。如下圖:
──────────┬────┬──────┬───────┬────────┬─────────┬────────┬─────────────┬──────────┐
│ 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 也不再生效。
解決辦法有兩種:
1. 使用-f 參數強制其更換啟動模式:pm2 start app.js -i 2 -f
2. 使用pm2 kill ,關閉deamon,然后重新使用pm2 start app.js開啟。
二、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)
可以看出,單進程情況下,抗住了將近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/