꼬반 Blog

nodejs + express + cluster 사용하기

====== nodejs + express + cluster 사용하기 ======

nodejs version : v0.10.26
express version : v4.0.0

앞서서 express 가 버전업이 많이 되면서 과거와 다르게 express 만 전역으로 설치해서는 자동으로

프로젝트를 생성해주지 않는다. express-generation 을 설치해야만 이전과 같이 자동으로 프로젝트를 생성할 수 있다.

<code>
$ npm install express-generation -g
</code>

이렇게 설치하고 자동으로 프로젝트를 생성하게 되면 이전 버전과는 실행방법에 약간 차이가 발생한다.
이전버전의 경우는 아래처럼 실행을 했다면

<code>
$ node app.js
</code>

4. 버전에서는

<code>
$ npm start
</code>

위와 같이 실행하여 준다. 그러면 bin 폴더내의 www 파일이 실행되어 지는데 살펴보면 기존 버전에서 server를 listen 하는
부분이 실행부분으로 분리가 되고 기존 app.js 는 export.module 로 사용되어지는 것 뿐. 방식은 동일하다.

이를 유의하여 cluster 를 적용하면 아래와 같이 된다. 아래 내용은 www 파일을 수정하여 적용한 것이다.


#!/usr/bin/env node
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
var debug = require('debug')('my-application');
var app = require('../app');

if(cluster.isMaster) {  for(var i=0;i    cluster.fork();
  }
  cluster.on('exit', function(worker, code, signal) {
    console.log('worker' + worker.process.pid + ' died');
    cluster.fork();
  });
} else {
  console.log(" worker:="" %s",="" process.pid);
  app.set('port', process.env.PORT || 3000);

  var server = app.listen(app.get('port'), function() {
    debug('Express server listening on port ' + server.address().port);
  });
}
위와 같이 작성하여 실행하여 보면 cpu core 갯수만큼 worker 가 생성되어 지는 것을 확인할 수 있다.
또한 worker 가 호출되는것을 확인하고자 한다면 router 에서 url 이 호출될때의 worker pid 를 확인하면 된다.

<code>
route/index.js

router.get('/', function(req, res) {
  console.log(process.pid);
  res.render('index', { title: 'Express' });
});
</code>

위와 같이 console.log() 로 process.pid 를 출력하여 보면 각기 다른 worker가 호출되는 것을 확인 할 수 있다.

참고1 : https://gist.github.com/ageldama/1546478
참고2: http://eclipse.or.kr/wiki/%ED%8A%B9%EC%A7%91%EA%B8%B0%EC%82%AC:Node_JS_%EB%A9%80%ED%8B%B0%EC%BD%94%EC%96%B4_CPU_%EC%A7%80%EC%9B%90%ED%95%98%EA%B8%B0

다만 cluster 를 사용하여 구성하는 경우 session 이나 socket.io 와 같이 내부 data 가 공유되지 못하는 부분이 발생하는데

이와 같은 부분인 redis 나 memcache 를 통해 해결할 수 있다.

참고3: http://nodeqa.com/nodejs_ref/55


반응형

Article By 꼬반

*certificate* : VCP 5(2012), RHCSA 7 (2014), RHCE 7 (2015), RHCSA in REDHAT OpenStack(2017) *development language* : Javascript, NodeJS, Golang, html5, css3, shell script *middle ware* : NGINX, Apache, Tomcat, Docker, Docker Swarm, Mesos, Kubernetes, HCI,

Discuss about post