在访问量大的场景中,会将session存储在redis中,下面将介绍在express框架中使用redis存储session
// db/redis.js
const redis = require('redis')
const redisClient = redis.createClient(port, host)
redisClient.on('error', err => {
console.log(err)
})
module.exports = redisClient
// app.js
...
const session = require('express-session')
const RedisStore = require('connect-redis')(session)
const redisClient = require('./db/redis')
const sessionStore = new RedisStore({
client: redisClient
})
app.use(session({
secret: 'xxxx',
cookie: {
maxAge: 24 * 60 * 60 * 1000
},
store: sessionStore // 存储在redis中
}))