您使用快遞,這樣連接,所以利用連接中間件。特別是會話中間件。 Connect的會話中間件具有商店的概念(某處存儲會話內容)。該存儲可以位於內存(默認)或數據庫中。所以,使用redis存儲(connect-redis)。
var express = require('express'),
RedisStore = require('connect-redis')(express),
util = require('util');
var redisSessionStoreOptions = {
host: config.redis.host, //where is redis
port: config.redis.port, //what port is it on
ttl: config.redis.ttl, //time-to-live (in seconds) for the session entry
db: config.redis.db //what redis database are we using
}
var redisStore = new RedisStore(redisSessionStoreOptions);
redisStore.client.on('error', function(msg){
util.log('*** Redis connection failure.');
util.log(msg);
return;
});
redisStore.client.on('connect', function() {
util.log('Connected to Redis');
});
app = express();
app.use(express.cookieParser());
app.use(express.session({
store: redisStore,
cookie: { path: '/',
httpOnly: true, //helps protect agains cross site scripting attacks - ie cookie is not available to javascript
maxAge: null },
secret: 'magic sauce', //
key: 'sessionid' //The name/key for the session cookie
}));
現在連接會話魔術會將會話詳細信息放在傳遞到每個路由的'req'對象上。 通過這種方式,您無需在整個地方傳遞redis客戶端。讓req對象爲你工作,讓你在每個路由處理器中免費得到它。
要確保你的: NPM安裝連接,Redis的
嘿嘿,謝謝... 它的工作原理... 我只是想知道,它連接到Redis的服務器再次,或使用現有連接以避免太多的開銷? –
並且沒有其他方法可以直接將redis對象傳遞給路由嗎? –
那麼,節點模塊一旦被加載就被緩存,所以沒有開銷......但實際的連接可能是新的。使用可重複使用連接的替代解決方案更新答案 – Kostia