Session實現原理javascript
實現請求身份驗證的方式不少,其中一種普遍接受的方式是使用服務器端產生的Session ID結合瀏覽器的Cookie實現對Session的管理,通常來講包括如下4個步驟:java
var session = require('express-session');
var RedisStrore = require('connect-redis')(session);
var config={
"cookie" : {
"maxAge" : 1800000
},
"sessionStore" : {
"host" : "192.168.0.13",
"port" : "6379",
"pass" : "123456",
"db" : 1,
"ttl" : 1800,
"logErrors" : true
}
app.use(session({
name : "sid",
secret : 'Asecret123-',
resave : true,
rolling:true,
saveUninitialized : false,
cookie : config.cookie,
store : new RedisStrore(config.sessionStore)
}));
實現堆棧
express-session實例化後調用代碼(https://github.com/expressjs/session)
if (!req.sessionID) { debug('no SID sent, generating session'); generate(); next(); return; }
generate方法調用(https://github.com/expressjs/session)
store.generate = function(req){ req.sessionID = generateId(req); req.session = new Session(req); req.session.cookie = new Cookie(cookieOptions); if (cookieOptions.secure === 'auto') { req.session.cookie.secure = issecure(req, trustProxy); } };
RedisStrore實例化時調用store.set(sid, session, callback)(https://github.com/expressjs/session)
store.set調用RedisStore.prototype.set(https://github.com/tj/connect-redis),其中座位hashkey使用的是前綴+sessonId,前綴默認值爲'sess',多個應用共享和不共享同一個redis session服務時,
必定要注意設置prefix
RedisStore.prototype.set = function (sid, sess, fn) { var store = this; var args = [store.prefix + sid]; if (!fn) fn = noop; try { var jsess = store.serializer.stringify(sess); } catch (er) { return fn(er); } args.push(jsess); if (!store.disableTTL) { var ttl = getTTL(store, sess); args.push('EX', ttl); debug('SET "%s" %s ttl:%s', sid, jsess, ttl); } else { debug('SET "%s" %s', sid, jsess); } store.client.set(args, function (er) { if (er) return fn(er); debug('SET complete'); fn.apply(null, arguments); }); };
store.client.set調用的爲(https://github.com/NodeRedis/node_redis)node
最終調用原生redis.hset方法git