# koa处理session

# 安装npm包

yarn add koa-session ioredis
1

# 添加session中间件


const session = require("koa-session")
const Redis = require("ioredis");

const RedisSessionStroe = require("./server/session-store")
//创建redisCline
const redis = new Redis();

const SESSION_CONFIG = {
        key: "jid",
        store: new RedisSessionStroe(redis)
    }
    server.use(session(SESSION_CONFIG, server))
1
2
3
4
5
6
7
8
9
10
11
12
13

session-store


function getRedisSessionId(id) {
    return `ssid:${id}`
}

class RedissSessionStore {
    constructor(client) {
        this.client = client
    }
    //获取redis中存储的session数据
    async get(sid) {
        // console.log("get session", sid)
        const id = getRedisSessionId(sid);
        const data = await this.client.get(id);
        if (!data) {
            return null;
        } else {
            try {
                return JSON.parse(data)
            } catch (error) {
                console.log(error)
            }
        }
    }
    //存储session数据到redis中
    async set(sid, sess, ttl) {
        // console.log("set session", sid)
        const id = getRedisSessionId(sid);
        if (typeof ttl === "number") {
            ttl = Math.ceil(ttl / 1000)
        }
        try {
            const sessStr = JSON.stringify(sess)
            if (ttl) {
                await this.client.setex(id, ttl, sessStr)
            } else {
                await this.client.set(id, sessStr)
            }
        } catch (error) {
            console.log(error)
        }
    }
    //从reids当中删除某个session
    async destroy(sid) {
        // console.log("destroy session", sid)
        const id = getRedisSessionId(sid)
        await this.client.del(id)
    }
}

module.exports = RedissSessionStore;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51