2013年7月18日 星期四

Express.js: Session for Production

Express.js Production Mode 啟動後會收到以下訊息
Warning: connection.session() MemoryStore is not designed for a production environment, as it will leak memory, and obviously only work within a single process.
避免造成 Memory Leak 方案如下
  1. no sessions - fast (438 req/sec)
  2. cookieSession: requires no external service, minor speed impact (311 req/sec) - fastest, sessions will expire with the cookie (customised by maxAge)
  3. connect-redis: requires redis server, large speed impact (4 req/sec with redis2go and redisgreen) - faster than mongo, sessions will be deleted after a while (customised by ttl)
  4. connect-mongo - requires mongodb server, large speed impact (2 req/sec with mongohq) - slower than redis, also has no way to remove sessions with no maxAge, requires manual clear_interval to be set to cleanup sessions

這邊我選用了 MongoDB 來作為解決方案

使用 connect-mongo 

INSTALL

  
$ npm install connect-mongo
  
mongoStore = require('connect-mongo')(express);
app.configure(function(){
    ...
    app.use(express.session({
        secret: "@#$TYHBVGHJIY^TWEYKJHNBGFDWGHJKUYTWE#$%^&*&^%$#",
        store: new mongoStore({
            host: setting.mongo.host,
            port: setting.mongo.port,
            db: 'examOnlineSessions',
            collection: 'sessions'
        })
    }));
    ...
})
With connect:
var connect = require('connect');
var MongoStore = require('connect-mongo')(connect);