koa2使用ioredis存储session

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值