node.js 如何从Redis保存和检索会话

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14014446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:48:53  来源:igfitidea点击:

How to save and retrieve session from Redis

node.jsredissession-state

提问by Eleeist

I am trying to integrate Redis sessions into my authentication system written in Node.js.

我正在尝试将 Redis 会话集成到我用 Node.js 编写的身份验证系统中。

I have been able to successfully set up Redis server, connect-redisand Express server.

我已经能够成功设置Redis服务器connect-redis和Express服务器。

Here is my setup (just the important bit):

这是我的设置(只是重要的一点):

var express = require("express");
var RedisStore = require("connect-redis")(express);
var redis = require("redis").createClient();

app.use(express.cookieParser());
app.use(express.session({
    secret: "thisismysecretkey",
    store: new RedisStore({ host: 'localhost', port: 6379, client: redis })
}));

Now... How do I actually create, read and destroy the session? I have read tons of articles on how to setup connect-redisand many questions here on SO, but I swear each one stops on just the configuration and does not explain how to actually use it...

现在...我如何实际创建、读取和销毁会话?我已经阅读了大量关于如何设置的文章connect-redis和许多关于 SO 的问题,但我发誓每一篇都只停留在配置上,并没有解释如何实际使用它......

I am aware that that is probably extremely simple, but please don't downvote and just explain :).

我知道这可能非常简单,但请不要投反对票,只是解释一下:)。

采纳答案by JohnnyHK

That should be all there is to it. You access the session in your route handlers via req.session. The sessions are created, saved, and destroyed automatically.

这应该就是全部了。您可以通过req.session. 会话会自动创建、保存和销毁。

If you need to manually create a new session for a user, call req.session.regenerate().

如果您需要为用户手动创建新会话,请调用req.session.regenerate()

If you need to save it manually, you can call req.session.save().

如果需要手动保存,可以调用req.session.save()

If you need to destroy it manually, you can call req.session.destroy().

如果需要手动销毁,可以调用req.session.destroy().

See the Connect documentationfor the full list of methods and properties.

有关方法和属性的完整列表,请参阅Connect 文档

回答by Shaikh Shahid

Consider this code.

考虑这个代码。

var express = require('express');
var redis   = require("redis");
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');
var client  = redis.createClient();
var app = express();

app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);

app.use(session({
    secret: 'ssshhhhh',
    // create new redis store.
    store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl :  260}),
    saveUninitialized: false,
    resave: false
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/',function(req,res){  
    // create new session object.
    if(req.session.key) {
        // if email key is sent redirect.
        res.redirect('/admin');
    } else {
        // else go to home page.
        res.render('index.html');
    }
});

app.post('/login',function(req,res){
    // when user login set the key to redis.
    req.session.key=req.body.email;
    res.end('done');
});

app.get('/logout',function(req,res){
    req.session.destroy(function(err){
        if(err){
            console.log(err);
        } else {
            res.redirect('/');
        }
    });
});

app.listen(3000,function(){
    console.log("App Started on PORT 3000");
});

So you need to install connect-redisand pass your express-sessioninstance to it.

所以你需要安装connect-redis并将你的express-session实例传递给它。

Then in middleware initialize redisStore with server details like this.

然后在中间件中使用这样的服务器详细信息初始化 redisStore。

app.use(session({
    secret: 'ssshhhhh',
    // create new redis store.
    store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl :  260}),
    saveUninitialized: false,
    resave: false
})); 

I put ttl to 260, you can increase. After TTL reaches its limits, it will automatically delete the redis key.

我把ttl设为260,可以增加。TTL 达到其限制后,它将自动删除 redis 密钥。

In routers you can use req.session variable to SET, EDIT or DESTROY the session.

在路由器中,您可以使用 req.session 变量来设置、编辑或销毁会话。

One more thing...

还有一件事...

If you want custom cookie i.e not as same as in your Redis store you can use cookie-parserto set cookie secrets.

如果您想要自定义 cookie,即与您的 Redis 商店中的cookie 不同,您可以使用cookie-parser来设置 cookie 秘密。

Hope it helps.

希望能帮助到你。

link : https://codeforgeek.com/2015/07/using-redis-to-handle-session-in-node-js/

链接:https: //codeforgeek.com/2015/07/using-redis-to-handle-session-in-node-js/

回答by decoder7283

You can also use the Redis monitor tool to see all the action in real time! When you refresh your app you will see the data appear in the console window.

您还可以使用Redis监控工具实时查看所有动作!当您刷新应用程序时,您将看到数据出现在控制台窗口中。

redis-cli monitor

Sample Output for Sessions using tj/connect-redis

使用 tj/connect-redis 的会话输出示例

1538704759.924701 [0 unix:/tmp/redis.sock] "expire" "sess:F9x-YgbgXu1g7RG8tFlkwY3RV0JzHgCh" "3600"
1538704759.131285 [0 unix:/tmp/redis.sock] "get" "sess:F9x-YgbgXu1g7RG8tFlkwY3RV0JzHgCh"
1538704787.179318 [0 unix:/tmp/redis.sock] "set" "sess:Hl3LPbOBdKO44SG4zQHFn2gfdiWTwzWW" "{\"cookie\":{\"originalMaxAge\":3600000,\"expires\":\"2018-10-05T02:59:47.178Z\",\"secure\":true,\"httpOnly\":true,\"domain\":\".indospace.io\",\"path\":\"/\"},\"path\":\"/\",\"userAgent\":{\"family\":\"NewRelicPingerBot\",\"major\":\"1\",\"minor\":\"0\",\"patch\":\"0\",\"device\":{\"family\":\"Other\",\"major\":\"0\",\"minor\":\"0\",\"patch\":\"0\"},\"os\":{\"family\":\"Other\",\"major\":\"0\",\"minor\":\"0\",\"patch\":\"0\"}},\"ip\":\"184.73.237.85\",\"page_not_found_count\":0,\"city\":\"Ashburn\",\"state\":\"VA\",\"city_state\":\"Ashburn, VA\",\"zip\":\"20149\",\"latitude\":39.0481,\"longitude\":-77.4728,\"country\":\"US\"}" "EX" "3599"
1538704787.179318 [0 unix:/tmp/redis.sock] "set" "sess:Hl3LPbOBdKO44SG4zQHFn2gfdiWTwzWW" "{\"cookie\":{\"originalMaxAge\":3600000,\"expires\":\"2018-10-05T02:59:47.178Z\",\"secure\":true,\"httpOnly\":true,\"domain\":\".indospace.io\",\"path\":\"/\"},\"path\":\"/\",\"userAgent\":{\"family\":\"NewRelicPingerBot\",\"major\":\"1\",\"minor\":\"0\",\"patch\":\"0\",\"device\":{\"family\":\"Other\",\"major\":\"0\",\"minor\":\"0\",\"patch\":\"0\"},\"os\":{\"family\":\"Other\",\"major\":\"0\",\"minor\":\"0\",\"patch\":\"0\"}},\"ip\":\"184.73.237.85\",\"page_not_found_count\":0,\"city\":\"Ashburn\",\"state\":\"VA\",\"city_state\":\"Ashburn, VA\",\"zip\":\"20149\",\"latitude\":39.0481,\"longitude\":-77.4728,\"country\":\"US\"}" "EX" "3599"