当前位置: 首页 > 工具软件 > ioredis > 使用案例 >

koa2使用ioredis存储session

汪学真
2023-12-01

koa2使用ioredis存储session

1. koa-session

安装

npm i koa-session ioredis

配置

const Redis = require('ioredis')
class SessionStore extends Redis{
  constructor(){
    super()
    this.redis = new Redis()
  }
  async set (key, sess, maxAge = 1000 * 60 * 60 * 24) {
    try {
      let data = await this.redis.set(
        `SESSION:${key}`,
        typeof sess == 'string' ? sess : JSON.stringify(sess),
        'EX',
        maxAge / 1000
      )
      return data
    } catch (error) {
      return error
    }
  }
  async get (key) {
    try {
      let data = await this.redis.get(`SESSION:${key}`)
      return JSON.parse(data)
    } catch (error) {
      return error
    }
  }
  async destroy (key) {
    try {
      let data = await this.redis.del(`SESSION:${key}`)
    } catch (error) {
      return error
    }
  }
}

const CONFIG = {
  key: 'SESSION' /** (string) cookie key (default is koa.sess) */,
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 1000*60*60*24,
  autoCommit: true /** (boolean) automatically commit headers (default true) */,
  overwrite: true /** (boolean) can overwrite or not (default true) */,
  httpOnly: true /** (boolean) httpOnly or not (default true) */,
  
  signed: true /** (boolean) signed or not (default true) secure: a boolean indicating whether the cookie is only to be sent over HTTPS (false by default for HTTP, true by default for HTTPS).*/,
  rolling: false /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */,
  renew: false /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/,
  // a boolean indicating whether the cookie is only to be sent over HTTPS (false by default for HTTP, true by default for HTTPS).
  secure: false /** (boolean)https secure cookie*/,
  sameSite: null /** (string) session cookie sameSite options (default null, don't set it) */,

  store: new SessionStore(),
}
module.exports = CONFIG

app.js引入

const session = require('koa-session')
const CONFIG = require('./config/session.config')
app.keys = ['some secret hurr'];

app.use(session(app,CONFIG));

使用

  ctx.session.key = "success";

参考

koa-session2

 类似资料: