Home Articles

redis保存会话和其他数据

Asked
Viewed 662 times
2

如何使用redis存储会话和其他数据?

我收到错误“myRedis Error-> Error:Redis连接到127.0.0.1:6379失败 - 连接ECONNREFUSED” . 没有myRedis部分,express / session / redis运行正常 .

var express = require('express');
var session = require('express-session');

// pass the express to the connect redis module
// allowing it to inherit from session.Store
var RedisStore = require('connect-redis')(session);

....
// Populates req.session
app.use(session({
  resave: false, // don't save session if unmodified
  saveUninitialized: false, // don't create session until something stored
  secret: 'keyboard cat',
  store: new RedisStore
}));

// needed for saving new data
var myRedis = require('redis');                           // additional redis store
var myRedisCli = myRedis.createClient();

myRedisCli.on('error', function (err) {
  console.log('myRedis Error-> '  + err);
});

有没有办法使用connect-redis的redis客户端?但看起来它与会话紧密结合 .

我无法找到有关这种情况的信息 . 希望有人能帮忙,谢谢!

1 Answer

  • 2

    在查看connect-redis代码之后,我终于发现可以将现有的redis-client传递给它 . 该文件提到了这一点,但没有举例说明 .

    以下代码有效 . 首先正常创建一个redis客户端,然后将其传递给会话 .

    var express = require('express');
    var session = require('express-session');
    
    var _myRedis = require('redis');                           // additional redis store
    var myRedisCli = _myRedis.createClient();
    
    // pass the express to the connect redis module
    // allowing it to inherit from session.Store
    var RedisStore = require('connect-redis')(session);
    
    ...
    
    app.use(session({
      resave: false, // don't save session if unmodified
      saveUninitialized: false, // don't create session until something stored
      secret: SESSION_SECRET,
      store: new RedisStore({client: myRedisCli})
    }));
    

Related