大脸猫脸大 2020-01-17
安装koa-session
yarn add koa-session
配置koa-session redis
const session = require(‘koa-session‘);
const Redis = require(‘ioredis‘);
const redis = new Redis();
// 配置koa-session
server.keys = [‘dev secret key‘];
const CONFIG = {
key: ‘ig‘,
store: new RedisSessionStore(redis)
};
server.use(session(CONFIG, server));
// 设置session
router.get(‘/set/user‘, async ctx => {
ctx.session.user = {
name: ‘js‘,
age: 29
};
ctx.body = ‘success‘;
});
server.use(router.routes()); koa-session store的配置
// 连接redis的一些方法
/**
* 返回实际使用的redis模块名
* @param {*} sid key
*/
function getSessionId(sid) {
return `ssid:${sid}`;
}
class RedisSessionStore {
constructor(client) {
// 传入一个redis实例
this.client = client;
}
/**
* 从redis获取session数据
* @param {*} sid key
*/
async get(sid) {
console.log(‘get sid‘,sid)
const id = getSessionId(sid);
const data = await this.client.get(id);
if (!data) {
return null;
}
try {
const result = JSON.parse(data);
return result;
} catch (err) {
console.error(err);
}
}
/**
* 存入session数据到redis
* @param {*} sid key
* @param {*} sess value
* @param {*} ttl 过期时间
*/
async set(sid, sess, ttl) {
console.log(‘set sid‘,sid)
const id = getSessionId(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 (err) {
console.error(err);
}
}
/**
* 从redis删除session数据
* @param {*} sid key
*/
async destroy(sid) {
const id= getSessionId(sid);
await this.client.del(id)
}
}
module.exports = RedisSessionStore以上。