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

node koa-session 用redis存储session

顾宸
2023-12-01

参考  https://www.npmjs.com/package/koa-session2

1 安装 

npm install koa-session2

2 app.js

const Koa = require('koa');
const app = new Koa();
const session = require('koa-session2');
const Store = require('./redis-store');
const config = {
    redis: {
      port: 6379,
      host: 'localhost',
      family: 4,
      password: '123456',
      db: 0
   },
}

app.use(session({
    store: new Store(config.redis),
    maxAge:1*60*60*1000
}));

 redis-store.js

const Redis = require("ioredis");
const { Store } = require("koa-session2");

class RedisStore extends Store {
    constructor(redisConfig) {
        super();
        this.redis = new Redis(redisConfig);
    }

    async get(sid, ctx) {
        let data = await this.redis.get(`SESSION:${sid}`);
        return JSON.parse(data);
    }

    async set(session, { sid =  this.getID(24), maxAge = 1000000 } = {}, ctx) {
        try {
            // Use redis set EX to automatically drop expired sessions
            await this.redis.set(`SESSION:${sid}`, JSON.stringify(session), 'EX', maxAge / 1000);
        } catch (e) {}
        return sid;
    }

    async destroy(sid, ctx) {
        return await this.redis.del(`SESSION:${sid}`);
    }
}

module.exports = RedisStore;

 

 类似资料: