我尝试在 NodeJS 中使用 Redis 的标准会话持久性:
var express = require('express');
var RedisStore = require('connect-redis')(express);
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
secret: "keyboard cat",
store: new RedisStore,
key: 'sid'
}));
});
app.get('/', function (req, res) {
if (req.session.isValid) {
console.log("There is an existing session.");
}
else {
req.session.isValid = true;
console.log("New session.");
console.log('Old session ID: ' + req.header('Cookie'));
console.log('New session ID: ' + req.session.id);
}
res.render('index', {'title': s});
});
app.listen(4000);
理论上我应该看到“新会话”这一行。网站站点的所有后续调用都应导致“存在现有会话”。不幸的是,每次通话都会重新生成一个新的会话 ID。浏览器中的 cookie 工作正常,内容正确传输,我可以在
req.header('Cookie')
这是控制台日志的样子:
[app.js] New session.
[app.js] Old session ID: undefined
[app.js] New session ID: nuoHKZj2j0AoRkvqT4xE5h6W.zF+DNv2rzr3kpeO2IyD7sa4xdamFQMugjfQvY6OYymE
[app.js] New session.
[app.js] Old session ID: sid=neLUc5PXxPoj1yFqukerv49x.BHzYKiuAfFSNHKd4fCAkv8wNwZO%2FxykJPN5R5tjAlQc
[app.js] New session ID: FvuzjnXvchCkmVqsq5mrodL2.5YlT3InfTbvOwEUc0dNpPLT77tcdJpNuhbFGVYkLneQ
[app.js] New session.
[app.js] Old session ID: sid=pFbyVdlNZXtF5vZ35CW9sfmq.nJ1RBjJu59iUJJjmZv9TCYiYLcvycme%2BJh8sQC6%2FzEE
[app.js] New session ID: KdPhwqwwgmOnPZEuVapy7EJe.I0TGT9HSSQQSporwCNsxl11rXDxR/ysjTeZb0lD5uwI
同时在redis-cli中运行“MONITOR”命令时得到以下输出:
sess:nuoHKZj2j0AoRkvqT4xE5h6W.zF+DNv2rzr3kpeO2IyD7sa4xdamFQMugjfQvY6OYymE
*2
$3
get
$73
sess:Q6Z06GL4hdRytKA2MToCIgVw.JWxImSB/m20Urn+IYMQqnNqfQp4ygAESiyBLORn3Iuo
*2
$3
get
$73
sess:neLUc5PXxPoj1yFqukerv49x.BHzYKiuAfFSNHKd4fCAkv8wNwZO/xykJPN5R5tjAlQc
*2
$3
get
$73
sess:FvuzjnXvchCkmVqsq5mrodL2.5YlT3InfTbvOwEUc0dNpPLT77tcdJpNuhbFGVYkLneQ
*2
$3
get
$73
sess:zvCWdwzowgAfl6jH8m0D31vL.b5tK5VZUJtPHrdvH09A/hjhjoOg6bT0CmAcWWRf99SI
*2
$3
get
$73
sess:pFbyVdlNZXtF5vZ35CW9sfmq.nJ1RBjJu59iUJJjmZv9TCYiYLcvycme+Jh8sQC6/zEE
*2
$3
get
$73
sess:KdPhwqwwgmOnPZEuVapy7EJe.I0TGT9HSSQQSporwCNsxl11rXDxR/ysjTeZb0lD5uwI
*2
$3
get
$73
sess:r793eaJyOnaq2RNyw1Hmpuwv.xnonbOlaWEAlpz+LDg0SHcUeAa0sbjyw0oIcwFmlX0w
当我使用 MemoryStore 而不是 RedisStore 时,一切都按预期工作。
有任何想法吗?