10.2.1 cluster 모듈 예제

    Node.js 공식 사이트에서 제공하는 cluster 모듈 예제 코드로 사용법을 알아보겠습니다. 원본은 https://nodejs.org/dist/latest-v6.x/docs/api/cluster.html에서 확인할 수 있습니다.

    다음과 같이 코드를 작성한 후 cluster.js로 저장합니다.

    코드 10-1 cluster 모듈 예제 코드

    예제 파일 : cluster.js

    const cluster = require('cluster');                 // ➊ cluster 모듈 로드
    const http = require('http');                       // ➋ http 모듈 로드
    const numCPUs = require('os').cpus().length;        // ➌ CPU 코어 수를 알아 옴
    
    if (cluster.isMaster) {                  // ➍ 부모 프로세스일 경우
        console.log(`Master ${process.pid} is running`);
    
        for (let i = 0; i < numCPUs; i++) {  // ➎ 코어 수만큼 자식 프로세스 실행
            cluster.fork();
        }
    
        cluster.on('exit', (worker, code, signal) => {  // ➏ 자식 프로세스 종료 이벤트 감지
            console.log(`worker ${worker.process.pid} died`);
        });
    } else {                                 // ➐ 자식 프로세스일 때 HTTP 서버 실행
        http.createServer((req, res) => {
            res.writeHead(200);
            res.end('hello world\n');
        }).listen(8000);
    
        console.log(`Worker ${process.pid} started`);
    }
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.