Node.js 성능 올리기
노드 인스턴스를 여러개 띄워 노드 앱의 성능을 향상시킬 수 있다.
- cluster로 직접 자식 프로세스를 만들기
- 편하게 pm2의 클러스터 모드 사용하기
- webworker-threads 모듈 사용하기
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// - cluster 모듈 사용하기 | |
const cluster = require('cluster') | |
if (cluster.isMaster) { | |
cluster.fork() | |
cluster.fork() | |
cluster.fork() | |
cluster.fork() | |
} else { | |
// server code | |
} | |
// - pm2 cluster 사용하기 | |
` | |
$ pm2 start index.js -i 0 | |
` | |
// -i 0 옵션을 주면 하드웨어에 알맞은 클러스터 개수가 설정된다. | |
// 내 맥에서는 4개가 돌아가게됨 | |
// - worker threads 사용하기 | |
const Worker = require('webworker-threads').Worker | |
const worker = new Worker(function() { | |
// 쓰레드에서 돌아갈 함수 | |
// 함수가 스트링 형태로 별개의 쓰레드에 보내진다. 그러므로 클로저 사용 불가 | |
this.onmessage = function() { | |
let counter = 0 | |
while (counter < 1e9) { | |
counter++ | |
} | |
postMessage(counter) // 내 코드에 보낼 데이터 | |
} | |
}) | |
worker.onmessage = function(message) { // 받을 데이터 핸들러 | |
console.log(message.data) | |
} | |
worker.postMessage() // 쓰레드 시작시키기 | |
// 프로파일링 하기 | |
` | |
$ ab -c 100 -n 100 localhost:3000/ | |
` | |
// ab -c 동시에 보낼 요청 개수, -n 보낼 요청 개수 url |